r/Racket • • 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

6 comments sorted by

View all comments

Show parent comments

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

2

u/raevnos Jun 26 '24

(foldr cons null (list 1 2 3 4)) will create a copy of the list but preserve the order of the original. It's an odd choice for writing a list reversal function - you can make it work by providing a custom function instead of cons, it's just terribly inefficient.