首页 > 解决方案 > 需要在使用之前更改函数的输入吗?

问题描述

我正在尝试编写一个函数,该函数接收两个表示自然数数字的列表,反向并求和它们。列表中也可能有任意数量的尾随 0。

plus :: [Int] -> [Int] -> [Int]
-- Ex: "plus [0,1,2,0] [2,1,0]" meaning 210+12

我有 3 个单独的函数来执行问题的不同部分,但我无法让它们一起工作:


cleanString将数字按顺序放回(最重要的在前)并删除任何额外的 0(cleanString [0,1,2,0]输出[2,1,0]):

fromDigits接受一个类似的列表[2,1,0]并给出210

那么实际的“加号”函数是我无法让它在输入列表cleanString进入fromDigits并添加生成的两个整数之前运行输入列表的地方。编译错误fromDigits (x.cleanString)


cleanString :: [Integer]->[Integer]
--reverse the string, then trim any leading zeroes
cleanString x = dropWhile(<1) y where y=reverse x

fromDigits :: [Integer] -> Integer
fromDigits xs = aux xs 0
    where aux [] acc = acc
          aux (x:xs) acc  = aux xs ((acc * 10) + x)

plus :: [Integer]->[Integer] -> Integer
plus x y = (fromDigits (x.cleanString))+(fromDigits (y.cleanString))

标签: haskell

解决方案


x不是一个函数,所以它对任何东西都没有意义.。你不应该这样做x.cleanString,而是应该这样做cleanString x。对y. 通过这些更改,您的程序似乎对我有用:

plus x y = (fromDigits (cleanString x))+(fromDigits (cleanString y))

如果你想使用.,即使你不需要,你可以,只是在函数上而不是 on xor y

plus x y = ((fromDigits.cleanString) x)+((fromDigits.cleanString) y)

推荐阅读