[英]Haskell Type Error From Function Application to Function Composition
這個問題與由antal sz回答的此功能組成VS功能應用程序有關。
你怎么能得到這個?
map has type (a -> b) -> [a] -> [b]
head has type [a] -> a
map head has type [[a]] -> [a]
為什么以下代碼的函數組成有類型錯誤?
test :: [Char] -> Bool
test xs = not . null xs
getMiddleInitials :: [String] -> [Char]
getMiddleInitials middleNames = map head . filter (\mn -> not . null mn) middleNames
但這沒有類型錯誤
getFirstElements :: [[a]] -> [a]
getFirstElements = map head . filter (not . null)
為了利用功能組合,是否必須編寫無點功能? 我仍然不太了解函數組合的用法。
請幫忙。 謝謝。
那只是因為函數應用程序xy
優先級高於合成x . y
優先級x . y
x . y
test :: [Char] -> Bool
test xs = (not . null) xs
-- # ^ ^
getMiddleInitials :: [String] -> [Char]
getMiddleInitials middleNames = (map head . filter (\mn -> (not . null) mn)) middleNames
-- # ^ ^ ^ ^
您在這里的錯誤實際上非常簡單。 如果您記得我對上一個問題的回答的最后部分,則是.
運算符的優先級高於除功能應用程序以外的任何優先級。 因此,請考慮您的示例
test :: [Char] -> Bool
test xs = not . null xs
這被解析為test xs = not . (null xs)
test xs = not . (null xs)
。 當然, null xs
類型為Bool
,並且您不能編寫布爾值,因此會出現類型錯誤。 因此,您可以使示例工作如下:
test :: [Char] -> Bool
test xs = (not . null) xs
getMiddleInitials :: [String] -> [Char]
getMiddleInitials middleNames =
(map head . filter (\mn -> (not . null) mn)) middleNames
當然,以這種方式編寫它是不尋常的,但是可以正常工作。
不,除了無點樣式外,還有函數組合的其他用途。 一個示例是將函數組合用於某些事物( 例如 map
或filter
的參數),但指定其余部分。 例如,以這個人為的例子為例:
rejectMapping :: (a -> Bool) -> (a -> b) -> [a] -> [b]
rejectMapping p f = map f . filter (not . p)
這部分是無點的(例如, not . p
,我們省略了最后一個參數),但是部分是無點的(存在p
和f
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.