配对2列表方案 [英] Pairing 2 lists Scheme

查看:74
本文介绍了配对2列表方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计划/球拍/R5RS

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

测试用例: (成对'(1 2 3)'(a b c)) 所需的输出:((1 .a)(2. b)(3 .c)) 当前输出:(1.a)

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

推荐答案

您只需要将当前结果cons递归调用该过程即可,就是这样!

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列表方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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