haskell - 需要在使用之前更改函数的输入吗?
问题描述
我正在尝试编写一个函数,该函数接收两个表示自然数数字的列表,反向并求和它们。列表中也可能有任意数量的尾随 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))
解决方案
x
不是一个函数,所以它对任何东西都没有意义.
。你不应该这样做x.cleanString
,而是应该这样做cleanString x
。对y
. 通过这些更改,您的程序似乎对我有用:
plus x y = (fromDigits (cleanString x))+(fromDigits (cleanString y))
如果你想使用.
,即使你不需要,你可以,只是在函数上而不是 on x
or y
:
plus x y = ((fromDigits.cleanString) x)+((fromDigits.cleanString) y)
推荐阅读
- python - 当有使用 Django 的可用选项时,是否需要依赖下拉菜单?
- configuration - 如何集成 IBM Rational Team Concert 和 Power bi 工具
- r - 在 barplot 的文本中的条上添加文本
- java - 在android中拍照后如何修复我的应用程序崩溃
- typescript - TS 编译器无法识别导入的类
- python - 根据日期在python中合并不同长度的数据帧
- c++ - 读取 QDomElement 的原始值
- oracle - 如何通过 sqlplus 假脱机解释 Oracle 的结果?
- python - 将带有反斜杠的stdin字符串存储到变量中
- r - r - 如何在 dabestr 中创建用于绘图的循环?