What's a recursive way to move the second elem

2019-07-29 23:03发布

问题:

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))

回答1:

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)


标签: scheme racket