Function 从函数应用程序到函数组合的Haskell类型错误

Function 从函数应用程序到函数组合的Haskell类型错误,function,haskell,types,function-composition,pointfree,Function,Haskell,Types,Function Composition,Pointfree,这个问题与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] -> [Ch

这个问题与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)
为了利用函数组合,必须编写一个无点函数吗? 我仍然不太了解函数组合的用法

请帮忙。
谢谢

这只是因为函数应用程序
xy
的优先级高于组合
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
这被解析为
testxs=not。(空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
)。

没有真正理解拒绝映射示例的最后一部分。您不理解其中的哪一部分?它背后的动机,它应该做什么,或者它是如何工作的?它只使用你已经看到的东西,所以如果你想一想,你应该能够遵循它!