Scheme,你如何附加一个带有单个项目的列表? [英] Scheme, how do you append a list with a single item?

查看:71
本文介绍了Scheme,你如何附加一个带有单个项目的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数来附加一个带有单个项目的列表.它正在做的是返回一个点对.

I'm trying to make a function to append a list with a single item. What it's doing though is returning a dot pair.

(define (append lst x)
  (cond
    ((null? lst) x)
    (else (cons (car lst) (append (cdr lst) x)))))

我得到的输出是

> (append '(1 2 3 4 5 6 7) 8)
(1 2 3 4 5 6 7 . 8)

我正在努力

(1 2 3 4 5 6 7 8)

谢谢.

推荐答案

试试这个:

(define (append lst x)
  (cond
    ((null? lst) (cons x '())) ; here's the change
    (else (cons (car lst) (append (cdr lst) x)))))

请注意,所有正确的列表必须以空列表结尾,否则会发生您刚刚经历的情况.换一种说法:

Notice that all proper lists must end in the empty list, otherwise it'll happen what you just experienced. To put it in another way:

(cons 1 (cons 2 3))
=> '(1 2 . 3) ; an improper list

(cons 1 (cons 2 (cons 3 '())))
=> '(1 2 3)   ; a proper list

这篇关于Scheme,你如何附加一个带有单个项目的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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