首页 > 解决方案 > 在haskell中添加两个列表的元素

问题描述

add_lists list1 list2:返回每个列表中相同位置的元素之和作为一个新列表。如果一个列表比另一个列表短,则假设较短的列表在“缺失的地方”中有零。这是我的haskell代码

add_lists list1 list2= if length.list1 < length.list2
                       then list2 ++ [i] && zipWith(+)list1 list2 
                       else zipWith (+) list1 list2
                       where [i|i=0,i=length.list2-length.list1]

我不断收到错误

标签: haskell

解决方案


在这里使用显式递归可能是最简单的。

add_lists [] list2 = list2
add_lists list1 [] = list1
add_lists (x:xs) (y:ys) = x + y : add_lists xs ys

推荐阅读