将列表的第二个元素移到前面的递归方法是什么?[球拍]



如何递归将3元素列表的中间移至列表的前面?有嵌套列表。

so,

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

应该变成

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

这是match的非常好的使用,因为我们可以为3元素列表设置条件,而只是忽略其他情况 -

(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在评论中捕获一个错误。这是修复 -

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

最新更新