2017-01-02 55 views
0

努力學習如何通過重新定義序幕功能使用的摺疊:如何在地圖中使用Haskell中的curried函數?

import Prelude hiding (sum, product, length, and, or, all, any, filter) 

到目前爲止,我起身到所有的工作,但我想不出什麼我做錯了一切。我如下定義它:

and :: [Bool] -> Bool 
and = foldr (&&) True 

... 

all :: (a -> Bool) -> [a] -> Bool 
all = and $ map 

但這顯示一條錯誤信息:

Probable cause: ‘map’ is applied to too few arguments 

我也試着將其定義爲:

and :: [Bool] -> Bool 
and = foldr (&&) True 

... 

all :: (a -> Bool) -> [a] -> Bool 
all f [xs] = and $ map f [xs] 

編譯沒有問題,但當我試圖稱它說:

[1 of 1] Compiling Fold    (Fold.hs, interpreted) 
Ok, modules loaded: Fold. 
*Fold> all even [0,2,4,6] 
*** Exception: Fold.hs:17:1-29: Non-exhaustive patterns in function all 

我不明白,因爲不應該[xs]匹配任何列表,甚至是空的列表?爲什麼我可以在不包含列表但不包含地圖的情況下咖喱foldr?任何幫助,將不勝感激。

+1

你的最後一個錯誤是因爲'[XS]'將只與一個元素匹配列表中的註釋。只需從參數和參數中去除「地圖」的方括號即可。 – Carcigenicate

+3

Downvoter應該評論,因爲答案或問題都不是那麼糟糕。 – Carcigenicate

+0

@Carcigenicate啊謝謝你有道理 – user6731064

回答

2

您將功能應用程序與構圖混合在一起。這有幫助嗎?

all :: (a -> Bool) -> [a] -> Bool 
all fn = and . (map fn) 

在實踐中,這等同於你的代碼+從@Carcigenicate

+0

沒有投票,但我認爲那些曾經希望你解釋'功能全部錯誤的非窮舉模式'的人。 – Alec

+1

@Simon H非常感謝你,顯然我需要重新編寫組合和應用程序 – user6731064

+0

注意:你確實需要有'fn'參數:'all =和。地圖'很好。 – Bakuriu