List 如何在Haskell中添加两个列表中的值(+;额外条件)

List 如何在Haskell中添加两个列表中的值(+;额外条件),list,haskell,numbers,List,Haskell,Numbers,我对这个练习有问题。我花了很长时间寻找资料,试图解决这个问题,但我做不到 定义功能: addLnat :: [Int] -> [Int] -> [Int] mulLnat :: [Int] -> [Int] -> [Int] addLnat将两个数组中的数字相加,例如 addLnat [4,5,6] [8,5,2] -> [2,1,9] 正如[4+8给出2进位1,5+5+1给出1进位1,6+2+1=9] Lnat是一个“列表自然数”,表示为以10位为基数的列表

我对这个练习有问题。我花了很长时间寻找资料,试图解决这个问题,但我做不到

定义功能:

addLnat :: [Int] -> [Int] -> [Int]
mulLnat :: [Int] -> [Int] -> [Int]
addLnat将两个数组中的数字相加,例如

addLnat [4,5,6] [8,5,2] ->  [2,1,9]
正如[4+8给出2进位1,5+5+1给出1进位1,6+2+1=9]

Lnat是一个“列表自然数”,表示为以10位为基数的列表,最低有效第一位。所以654是[4,5,6]

我得到的是:

addLnat :: [Int] -> [Int] -> [Int]
addLnat _ [] = []
addLnat [] _ = []
addLnat (x:xs) (y:ys) = (if (x+y) > 9 then x+y-10 else (x+y)):(addLnat xs ys)
我加上数字,忽略进位。不知道怎么解决。 任何帮助都将不胜感激。


我已根据user5402注释改进了解决方案,因此创建了addLnat'cr xs ys,但当我将什么作为参数传递进位时,它无法加载-很可能是语法错误:( (cr目前仅为0,将由数学替换)

addLnat'c(x:xs)(y:ys)=d:addLnat'cr-xs-ys
其中d=如果c+x+y<9,则x+y否则c+x+y-((c+x+y)10)*10)
cr=0

有什么想法吗?

您需要编写一个接受进位参数的addLnat版本:

addLnat' c (x:xs) (y:ys) = d : addLnat c' xs ys
  where d = if c+x+y > 9 then ... else ...
        c' = ... the next carry bit ...
有更多的细节和拐角的情况需要考虑,但这是基本的想法。 最后,


我不太擅长haskell,但这可能会有所帮助

add::[Int]->[Int]->[Int]
add x y = add' 0 x y
在这里,我们定义了一个函数add,它将使用add'来添加两个列表。其主要思想是“保存”进位并仔细处理角盒。这里进位保存在“变量”rest中

列表x必须大于列表y,但这不是问题

add [5,7,8] [4,3,2]  => [9,0,1,1] (correct)
add [1,2,3] [4,5,6]  => [5,7,9,0] (correct)

这里有一个提示:尝试定义一个helper函数
addLnatCarry::Int->[Int]->[Int]->[Int]->[Int]
,该函数的第一个参数是一个进位数字(或者一个
Bool
告诉你是否有进位,如果你愿意的话)。Pro提示:
[Int]
不是数组。它是一个列表。谢谢-将主题中的数组改为列表。这是我的想法,但这是我从一个了解这些东西的人那里得到的。非常感谢你的帮助:-)这是我开始使用它时的方式。这是我得到的工作(不包括实数进位)addLnat'c(x:xs)(y:ys)=d:addLnat'0xsys其中d=如果c+x+y<9那么x+y其他c+x+y-((quot(c+x+y)10)*10)当我想包括实数进位作为变量时,它在addLnat'c(x:xs)(y:ys)=d:addLnat'crxs ys其中d=如果c+x+y<9那么x+y其他c+x+y-((c+x+y)10)*10) cr=0我猜语法错误,但我无法正确理解:-(
add::[Int]->[Int]->[Int]
add x y = add' 0 x y
    add'::Int->[Int]->[Int]->[Int]
    add' 0 x []      = x 
    add' rest (x:[]) (y:[]) = [(r `mod` 10),(r `div` 10)]
       where r = x+y+rest
    add' y (x:xs) [] = add' (r `div` 10) ((r `mod` 10):xs) [] 
       where r = x+y
    add' rest (x:xs) (y:ys) = (r `mod` 10) : (add' (r `div` 10) xs ys)
       where r = x+y+rest 
add [5,7,8] [4,3,2]  => [9,0,1,1] (correct)
add [1,2,3] [4,5,6]  => [5,7,9,0] (correct)