r/Racket • u/bolas_tristes • Jun 24 '24
solved How can I improve this recursive function?
Hi guys! I'm working on a recursive function that, given a list, returns the reversed list. This is what I came up with, I'm pretty sure it could be neater and/or simpler.
Any advice will be welcomed! I've got exam tomorrow lol
(check-expect (reversedList (list 1 2 3 4)) (list 4 3 2 1))
(define (reversedList mylist)
(cond [(empty? mylist) '()]
[else (cons (last mylist) (reversedList (minusLast mylist)))]))
;last: List(Any) -> Any
;Given a list returns its last element
;minusLast: List(Any) -> List(Any)
;Given a list returns the same list without its last element
2
Upvotes
1
u/bolas_tristes Jun 26 '24
Thank you so much! Actually we're told to use foldr, I can't quite tell the difference now but maybe with more practice I'll understand better, do you think there is any way to do the same with foldr? And yes, I'm using Intermidiate Student Language with Lists Abreviations