cheezepops
cheezepops

Reputation: 13

What's a recursive way to move the second element of a list to the front? [Racket]

How can I recursively move the middle of a 3-element list to the front of the list? There are nested lists.

So,

 ((not #f) iff (((#f implies #t) and #t) or #f))

Should become

(iff (not #f) (or (and (implies #f #t) #t) #f))

Upvotes: 1

Views: 139

Answers (1)

Mulan
Mulan

Reputation: 135197

It's a really good use of match because we can set a condition for the 3-element list and simply ignore the other cases -

(define (transform l)
  (match l
    ((list a b c)
     (list (transform b)
           (transform a)
           (transform c)))
    (_
     l)))

(transform '((not #f) iff (((#f implies #t) and #t) or #f)))
; '(iff (not #f) (or (and (implies #f #t) #t) #f))

@PetSerAl catches a bug in the comments. Here's the fix -

(define (transform l)
  (match l
    ((list a b c)             ; a 3-element list
     (list (transform b)
           (transform a)
           (transform c)))
    ((? list? _)              ; any other list
      (map transform l))
    (_                        ; a non-list
     l)))

(transform '(not (#f implies #t)))
; '(not (implies #f #t)

Upvotes: 1

Related Questions