如何在球拍中手动拉平列表(方案) [英] How to manually flatten a list in Racket (Scheme)

查看:83
本文介绍了如何在球拍中手动拉平列表(方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果不使用球拍内置的拉平功能,如何拉平列表?

How could one go about flattening a list without using the flatten function built in to racket?

我知道Flatten的默认实现是

I understand that the default implementation of flatten is

(define (flatten lst)
  (cond 
    ((null? list)
      empty)
    ((list? (car lst))
      (append (flatten (car lst)) (flatten (cdr lst))))
    (else
      (cons (car lst) (flatten (cdr lst))))))

但是我不完全确定如何不使用flatten函数,因为我不知道它在幕后如何工作.除了此代码的实现之外,我找不到很好的解释.有人可以解释一下

but im not entirely sure how to go about not using the flatten function as I do not know how it is working behind the scenes. I couldn't find a good explanation of this besides implementations of this code. Could someone please explain

这是我非常糟糕的尝试,并且我几乎一无所知,因为这甚至还没有结束,并且将无法运行....

This is my very bad attempt and im pretty much clueless because this is not even close and will not run....

(define acc null)
(define (my-flatten lst)
  (cond
    [(null? lst) null]
    [(list? (car lst)) (help-flatten (car lst)) (append (cdr lst) acc)]
    [else (append (car lst) acc) (my-flatten (cdr lst))]))

(define (help-flatten subLst)
  (if (null? subLst)
      (set! acc null)
      (append (car subLst) acc))
  (help-flatten (cdr subLst)))

推荐答案

所示的第一个实现是自包含的,但不正确,它没有调用Racket的内置flatten-它只是递归地调用自身,将其重命名以查看我的意思是.这是固定版本:

The first implementation shown is self-contained but incorrect, and it's not calling Racket's built-in flatten - it's simply calling itself recursively, rename it to see what I mean. Here's a fixed version:

(define (my-flatten lst)
  (cond ((null? lst) empty) ; you wrote `list` instead of `lst`
        ((pair? (car lst))  ; it's more efficient if we use `pair?`
         (append (my-flatten (car lst)) (my-flatten (cdr lst))))
        (else (cons (car lst) (my-flatten (cdr lst))))))

或更简单:

(define (my-flatten lst)
  (cond ((null? lst) '())
        ((pair? lst)
         (append (my-flatten (car lst)) (my-flatten (cdr lst))))
        (else (list lst))))

这篇关于如何在球拍中手动拉平列表(方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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