将列表的第二个元素移到前面的递归方法是什么?[球拍] [英] What's a recursive way to move the second element of a list to the front? [Racket]

查看:31
本文介绍了将列表的第二个元素移到前面的递归方法是什么?[球拍]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何递归地将 3 元素列表的中间移动到列表的前面?有嵌套列表.

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

所以,

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

应该变成

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

推荐答案

match 因为我们可以为 3 元素列表设置一个条件并简单地忽略其他情况 -

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 在评论中发现了一个错误.这是修复 -

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

这篇关于将列表的第二个元素移到前面的递归方法是什么?[球拍]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆