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

ぐ巨炮叔叔 提交于 2019-12-12 22:34:02

问题


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)


来源:https://stackoverflow.com/questions/55193780/whats-a-recursive-way-to-move-the-second-element-of-a-list-to-the-front-racke

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!