簡體   English   中英

沒有最后一個參數的函數組成

[英]Composition of functions without last arguments

為什么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.
_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

如果要將第三個示例放入無點符號,則可以使用無點程序

> pointfree "_func x = sum . takeWhile (<10000) . filter odd . map x"

產量

_func = ((sum . takeWhile (< 10000) . filter odd) .) . map

不過,老實說,我認為這是給無點表示法起一個壞名字的例子之一,我只保留變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM