Programming, Racket

How to reverse a list recursively in Racket

(define (yani-reverse L) [if (null? L) null [append (yani-reverse (rest L))(list [first L])]])

In plain racket, define is used to define functions and variables.
The syntax, comes (define id expr) or (define (head args) body++)
Above I defined a function called yani-reverse with L as argument which in this case is a list, parenthesizes and square brackets are interchangeable. I’m doing a if statement that will check if my L ( list) is not null, if it’s null it will return null, if else it will append the last element of the list into an a list with the first element.
First is the first element of the list and rest of the rest elements of the list.

Lets now call our function

(yani-reverse '(a b c d))

(yani-reverse '(1 2 3 4))

(yani-reverse '( ))

'(d c b a)
'(4 3 2 1)

How did you like it?

3 comments on “How to reverse a list recursively in Racket

  1. Pingback: 情趣用品

  2. Pingback: Cheap Oakley Sunglasses Wholesale

Leave a Reply