【问题标题】:Mapping over two lists with uneven lengths - Scheme映射两个长度不均匀的列表 - 方案
【发布时间】:2021-11-12 08:20:57
【问题描述】:

我正在实现一个过程“map2”,它接收两个列表并返回每个元素的总和。如果列表不均匀,则仅返回最短列表的总和。我的代码是:

(define (map2 proc items1 items2)
  (if (null? items1)
    '()
    (cons (proc (car items1) (car items2))
          (map2 proc (cdr items1) (cdr items2)))))

使用示例应该是:

(maps2 + '(1 2 3 4) '(3 4 5)) --> (4 6 8)

我的问题是如何实现处理不均匀列表的部分?

【问题讨论】:

    标签: list mapping scheme


    【解决方案1】:

    您的解决方案几乎是正确的 - 您只需检查两个列表并在其中一个为空时停止。

    (define (map2 proc items1 items2)
      (if (or (null? items1) (null? items2))
        '()
        (cons (proc (car items1) (car items2))
              (map2 proc (cdr items1) (cdr items2)))))
    

    例子:

    > (map2 + '(1 2 3 4) '(3 4 5))
    '(4 6 8)
    > (map2 * '(1 2) '(3 4 5))
    '(3 8)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 2013-10-18
      • 2022-06-10
      • 2013-06-15
      • 2020-07-21
      • 2016-06-29
      • 1970-01-01
      • 2017-01-07
      相关资源
      最近更新 更多