Warning: Undefined array key "hide_archive_titles" in /home1/smartva9/public_html/smartvania/wp-content/themes/baton/includes/theme-functions.php on line 254

Category: 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)
'()