这个问题与Function Composition VS Function Application有关,由antal s-z回答。
你怎么能得到这个?
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)
为了利用功能组合,是否必须编写无点功能?
我仍然不太了解函数组合的用法。
请帮忙。
谢谢。
最佳答案
您在这里的错误实际上非常简单。如果您还记得my answer to your last question的最后一部分,那么.
运算符的优先级比函数应用程序之外的任何事物高。因此,请考虑您的示例
test :: [Char] -> Bool
test xs = not . null xs
这被解析为
test xs = not . (null xs)
。当然,null xs
的类型为Bool
,并且您不能编写 bool(boolean) 值,因此会出现类型错误。因此,您可以使示例工作如下: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
)。
关于function - 从功能应用到功能组合的Haskell类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3123457/