[英]I need to merge two lists in Scheme, taking one element from each one
這是我寫的:
(: mmm : (Listof Any) (Listof Any) -> (Listof Any))
(define (mmm list1 list2)
(cond [(or (null? list1) (null? list2)) null]
(and (cons (first list1) (first list2)) (mmm (rest list1) (rest list2)))))
我舉一個例子:
list1: a b c
list2: 1 2 3
answer: ((a 1) (b 2) (c 3))
編輯他們都一樣大小
如果允許使用map
,則可以使用:
(define (mmm lst1 lst2) (map (lambda (x y) (list x y)) lst1 lst2))
您的代碼有兩個問題:
else
開始(因為這是最后一個條件,並且條件是互斥的),而不是and
cons
編調用遞歸的結果 要修復它們,請嘗試以下操作-假設輸入列表的長度相等:
(define (mmm list1 list2)
(cond [(or (null? list1) (null? list2)) null]
[else (cons (list (first list1) (first list2))
(mmm (rest list1) (rest list2)))]))
現在,該過程按預期工作:
(mmm '(a b c ) '(1 2 3))
=> '((a 1) (b 2) (c 3))
如果您知道列表的大小相同,那么它將變得簡單:
(define (mmm list1 list2) (map list list1 list2))
注意:如果這是您真正想要的,請用map cons
替換map list
。 您的代碼使用了cons
但是您的結果示例表明該list
就是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.