我正在尝试通过在现有列表中添加数字来创建列表。问题是现有列表实际上不一定是列表。它可以是空列表((list )
),只是数字或实际列表。
基本上,我需要append
这样的东西,但它必须能够处理这种情况:
(append 1 2)
并生成列表(list 1 2)
除了典型案例:
(append (list 1 2) 3)
对第一个案例使用append会给我错误append: expected argument of type <proper list>; given 1
是否有类似append
的内容可以处理这两种情况?或者还有其他方法可以做到这一点吗?
谢谢!
答案 0 :(得分:2)
尝试这个简单的程序并告诉我它是否能解决您的问题:
#lang racket
(define (apnd a b)
(flatten (cons a b))
)
#test
(apnd 1 2)
(apnd (list 1 2) (list 3 4))
(apnd '() 1)
(apnd 1 '())
(apnd '() '())
(apnd (list 1 2) 3)
(apnd 1 (list 2 3))
参考文献:flatten
答案 1 :(得分:2)
这是一个非常简单的解决方案,遵循How to Design Programs的设计方法。
;; An Input is one of
;; - Number
;; - Listof[Number]
;; to-list : Input -> Listof[Number]
;; convert the input to a list if necessary
(define (to-list v)
(cond [(number? v) (list v)]
[else v]))
;; append* : Input Input -> Listof[Number]
;; append two inputs, converting to lists first if necessary
(define (append* a b)
(append (to-list a) (to-list b)))
答案 2 :(得分:2)
Welcome to Racket v5.1.1.
-> ;; First, you gave this example
(append (list 1 2) 3)
'(1 2 . 3)
-> ;; but notice that's not a proper list
(list? '(1 2 . 3))
#f
-> ;; you probably meant
(append (list 1 2) (list 3))
'(1 2 3)
-> ;; which is a list
(list? '(1 2 3))
#t
-> ;; I would make something like Sam's function
;; but it converts anything to a list
(define (any->list x)
(cond
[(list? x) x]
[else (list x)]))
-> ;; So for example:
(any->list 1)
'(1)
-> (any->list (list 1))
'(1)
-> ;; and then you use that in a variation of append
(define (my-append a b)
(append (any->list a) (any->list b)))
-> ;; so you can do any of these:
(my-append 1 2)
'(1 2)
-> (my-append '(1) 2)
'(1 2)
-> (my-append 1 '(2))
'(1 2)
-> (my-append '(1) '(2))
'(1 2)
->
答案 3 :(得分:0)
我会编写一个函数来执行此操作。
编辑:正如另一个人所说,这看起来像家庭作业。基本上你想在函数中使用条件来检查它是否是一个列表并相应地采取行动。