Haskell:嵌套括号与点符号
Haskell: nested parens vs. dot notation
欧拉计划的问题2说:
斐波那契数列中的每个新项都是通过添加前两项生成的。从 1 和 2 开始,前 10 项将是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
考虑斐波那契数列中不超过四百万的项,求偶数项之和。
GHCi 很好地解析了这个解决方案:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
p002fibsum x = sum (filter even (takeWhile (< (x+1)) fibs))
...但是这个有问题:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
p002fibsum x = sum . filter even . takeWhile (< (x+1)) fibs
Couldn't match expected type `a1 -> [c0]' with actual type `[a0]'
In the return type of a call of `takeWhile'
Probable cause: `takeWhile' is applied to too many arguments
In the second argument of `(.)', namely
`takeWhile (< (x + 1)) fibs'
In the second argument of `(.)', namely
`filter even . takeWhile (< (x + 1)) fibs'
takeWhile 似乎只接受两个参数,这似乎是正确的数量。我是否因为缺少类型签名而失败?我怎样才能让这个解决方案与点符号一起工作?
问题是 takeWhile (< (x+1)) fibs
的类型是 [a0]
(其中 a0
是一些 Num
),而函数组合需要一个函数作为它的第二个参数( a1 -> [c0]
).
如果你想使用点符号,那就是
p002fibsum x = (sum . filter even . takeWhile (< (x+1))) fibs
尽管我更愿意使用美元符号:
p002fibsum x = sum $ filter even $ takeWhile (< (x+1)) fibs
欧拉计划的问题2说: 斐波那契数列中的每个新项都是通过添加前两项生成的。从 1 和 2 开始,前 10 项将是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
考虑斐波那契数列中不超过四百万的项,求偶数项之和。
GHCi 很好地解析了这个解决方案:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
p002fibsum x = sum (filter even (takeWhile (< (x+1)) fibs))
...但是这个有问题:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
p002fibsum x = sum . filter even . takeWhile (< (x+1)) fibs
Couldn't match expected type `a1 -> [c0]' with actual type `[a0]'
In the return type of a call of `takeWhile'
Probable cause: `takeWhile' is applied to too many arguments
In the second argument of `(.)', namely
`takeWhile (< (x + 1)) fibs'
In the second argument of `(.)', namely
`filter even . takeWhile (< (x + 1)) fibs'
takeWhile 似乎只接受两个参数,这似乎是正确的数量。我是否因为缺少类型签名而失败?我怎样才能让这个解决方案与点符号一起工作?
问题是 takeWhile (< (x+1)) fibs
的类型是 [a0]
(其中 a0
是一些 Num
),而函数组合需要一个函数作为它的第二个参数( a1 -> [c0]
).
如果你想使用点符号,那就是
p002fibsum x = (sum . filter even . takeWhile (< (x+1))) fibs
尽管我更愿意使用美元符号:
p002fibsum x = sum $ filter even $ takeWhile (< (x+1)) fibs