将两个由3个字符组成的列表组合成3对 [英] Combine two lists of 3 characters into 3 pairs

查看:79
本文介绍了将两个由3个字符组成的列表组合成3对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此有点麻烦.基本上,我需要一个过程comb,它接受两个列表(comb '(a b c) '(1 2 3)并返回('a 1)('b 2)('c 3).我想出了一部分鳕鱼,它返回了第一对.

I'm having a little trouble with this. Basically, I need a procedure comb that takes two lists (comb '(a b c) '(1 2 3) and returns ('a 1)('b 2)('c 3). I came up with a part of the cod which returns the first pair

(define some-letters '(a b c))
(define some-nums '(1 2 3))
(define x (first (foldr cons empty some-letters)))
(define y (first (foldr cons empty some-nums)))
(define (comb list1 list2)
  (cond
   [(empty? list1) empty]
   [(empty? list2) empty]
    [else (list x y)]))

现在,我花了一些时间修改了一下,并提出了不同的定义comb:

Now, I tinkered around a little bit longer and came up with defining comb a bit differently:

(define (comb list1 list2)
  (cond
   [(empty? list1) empty]
   [(empty? list2) empty]
    [else ((list x y) (zip (rest list1) (rest list2)))]))

但这会返回以下内容:

function call: expected a function after the open parenthesis, but received (list 'a 1)

希望您能提供任何帮助.

I would appreciate any assistance you can provide.

推荐答案

您的实现存在两个问题:

There are two problems with your implementation:

  • 您忘记了cons正在构建的输出列表中的当前元素
  • 您将函数命名为comb,而不是zip(尽管该函数通常称为zip),因此在执行递归调用时必须使用comb
  • You forgot to cons the current element in the output list that's being built
  • You named the function comb, not zip (although this function is usually known as zip), therefore comb must be used when performing the recursive call

这可以解决问题:

(define (comb list1 list2)
  (cond
    [(empty? list1) empty]
    [(empty? list2) empty]
    [else (cons (list (first list1) (first list2))
                (comb (rest list1) (rest list2)))]))

或者尝试使用更简单的实现方法,但要注意的是,该警告仅适用于具有相同长度的列表:

Or try this for an even simpler implementation, with the caveat that only works for lists with the same length:

(define (comb list1 list2)
  (map list list1 list2))

这篇关于将两个由3个字符组成的列表组合成3对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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