Pairing 2 lists Scheme

六月ゝ 毕业季﹏ 提交于 2019-12-11 07:23:52

问题


SCHEME/Racket/R5RS

Attempting to make a recursive procedure that pairs 2 lists of the same size. Just cant get the recursive call right. This is what I have and I am stuck.

(define (pairs list1 list2)
  (if (or (null? list1) (null? list2))
      '()
        (cons (car list1) (car list2))
        ))

Test Case: (pairs '(1 2 3) '(a b c)) Desired Output: ((1 . a) (2 . b) (3 . c)) Current Output: (1 . a)


回答1:


You just have to cons the current result to the recursive call of the procedure, and that's it!

(define (pairs list1 list2)
  (if (or (null? list1) (null? list2))
      '()
      (cons (cons (car list1) (car list2))
            (pairs (cdr list1) (cdr list2)))))



回答2:


Would this be an acceptable solution as well?

(define pairs
      (lambda (x y)
        (map cons x y)))


来源:https://stackoverflow.com/questions/40538638/pairing-2-lists-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!