为什么func4
无效?我尝试加载它时遇到异常。
-- Works fine
func::Integer
func = sum . takeWhile (<10000) . filter odd . map (^2) $ [1..]
-- Works fine
func2::Integer
func2 = sum . takeWhile (<10000) . filter odd $ map (^2) [1..]
-- Works fine
func3::Integer
func3 = _func [1..]
where _func = sum . takeWhile (<10000) . filter odd . map (^2)
--Doesn't work!
func4::Integer
func4 = _func (^2) [1..]
where _func = sum . takeWhile (<10000) . filter odd . map
异常消息:
src.hs:3:63:
Couldn't match type `[a] -> [b]' with `[c]'
Expected type: (a -> b) -> [c]
Actual type: (a -> b) -> [a] -> [b]
Relevant bindings include
_func :: (a -> b) -> c (bound at src.hs:3:15)
Probable cause: `map' is applied to too few arguments
In the second argument of `(.)', namely `map'
In the second argument of `(.)', namely `filter odd . map'
Failed, modules loaded: none.
答案 0 :(得分:2)
_func (^2) [1..]
与
相同(sum . takeWhile (<10000) . filter odd . map) (^2) [1..]
而不是
sum . takeWhile (<10000) . filter odd . map (^2) $ [1..]
有点明显(对我来说)原因。
其中一个可能的解决方案是让_func
获取映射函数:
func4::Integer
func4 = _func (^2) [1..]
where _func f = sum . takeWhile (<10000) . filter odd . map f
答案 1 :(得分:2)
如果你想把第三个例子放在pointfree表示法中,你可以使用无点程序
> pointfree "_func x = sum . takeWhile (<10000) . filter odd . map x"
产量
_func = ((sum . takeWhile (< 10000) . filter odd) .) . map
老实说,我认为这是一个让无点符号成为坏名字的例子之一,我只是保留变量。