function - 从功能应用到功能组合的Haskell类型错误

标签 function haskell types function-composition pointfree

这个问题与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

当然,以这种方式编写它是不寻常的,但是可以正常工作。

不,除了无点样式外,还有其他功能组合的用途。一个示例是将函数组合用于某些事物(例如mapfilter的参数),但指定其余内容。例如,以这个人为的例子为例:
rejectMapping :: (a -> Bool) -> (a -> b) -> [a] -> [b]
rejectMapping p f = map f . filter (not . p)

这部分是无点的(例如,not . p,我们省略了最后一个参数),但是部分是无点的(存在pf)。

关于function - 从功能应用到功能组合的Haskell类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3123457/

相关文章:

haskell - 重做标准类

c# - 试图将字符串解析为 DateTime 格式 "02/01/2010"dd/MM/yyyy 而不是 "1/2/2010 MM/dd/yyyy

Javascript 检查函数参数

C: 函数返回指针

c - C 中的链表和结构 - 在函数中将链表和结构作为参数传递(C)

javascript - 这个数组过滤器中的函数是如何工作的?

haskell - ruby while 循环转换为 haskell

haskell - "try"回溯了多远?

javascript - React typescript 不可分配给类型参数

c++ - "long"和 "long int"之间的区别,abs & labs