2011-11-23 84 views
1

我试图通过向现有列表添加编号来创建列表。问题是现有的列表实际上不一定是列表。它可以是一个空列表((list)),只是一个数字或实际列表。从计划中编号和编号或列表和编号构建列表

基本上,我需要像append但它必须能够处理这种情况:

(append 1 2)并生成一个列表(list 1 2)

除了典型案例:

(append (list 1 2) 3)

使用第一个案例的追加给我的错误append: expected argument of type <proper list>; given 1

是否有类似append可以处理这两种情况?或者有其他方法可以做到这一点吗?

谢谢!

+0

这似乎是一个功课,我(你应该相应地标记)。顺便有这个清单?功能可以帮助您 – Eineki

+0

您使用哪种语言级别? – Eineki

+0

我只是想学习计划。这不是功课。 – Computerish

回答

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

0

我会写一个函数来做到这一点。

编辑:正如其他人所说,这看起来像是功课。基本上你想在函数中使用一个条件来检查它是否是一个列表并相应地执行。

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