从函数应用到函数组合的Haskell类型错误 [英] Haskell Type Error From Function Application to Function Composition

查看:90
本文介绍了从函数应用到函数组合的Haskell类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与这个函数组合VS函数应用相关,它由antal SZ。

This question is related to this Function Composition VS Function Application which answered by antal s-z.

你如何得到这个?

How you can get this ?

map has type (a -> b) -> [a] -> [b]
head has type [a] -> a
map head  has type [[a]] -> [a]

为什么下面的代码对函数组合有类型错误?

Why the following code has type error for function composition ?

 test :: [Char] -> Bool
 test xs = not . null xs

 getMiddleInitials :: [String] -> [Char]
 getMiddleInitials middleNames = map head . filter (\mn -> not . null mn) middleNames

但这没有类型错误

but this does not have type error

getFirstElements :: [[a]] -> [a]
getFirstElements = map head . filter (not . null)

是否必须编写一个点自由函数才能利用功能组成?
我还是不太了解函数组合的用法。

Is it a must to write a point free function in order to utilize the function composition ? I still not very understand the usage of function composition.

请帮忙。
谢谢。

Please help. Thanks.

推荐答案

这里的错误其实很简单。如果您还记得我对您最后一个问题的回答的最后部分,对于函数应用,运算符的优先级高于,除了。因此,考虑你的例子

Your error here is actually really simple. If you remember the last part of my answer to your last question, the . operator has higher precedence than anything except for function application. Thus, consider your example of

test :: [Char] -> Bool
test xs = not . null xs

解析为 test xs = not。 (null xs)。当然, null xs 的类型是 Bool ,并且你不能编写布尔值,所以你得到一个类型错误。因此,你可以让你的例子像这样工作:

This is parsed as test xs = not . (null xs). Of course, null xs has type Bool, and you can't compose a boolean, and so you get a type error. Thus, you could make your examples work like so:

test :: [Char] -> Bool
test xs = (not . null) xs

getMiddleInitials :: [String] -> [Char]
getMiddleInitials middleNames =
  (map head . filter (\mn -> (not . null) mn)) middleNames

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

Of course, writing it this way is unusual, but it would work fine.

功能组合除了无点式之外的其他用途。一个例子是使用函数组合来处理某些事情( eg 参数为 map filter ),但指定其余的。举个例子:

And no, there are other uses of function composition besides point-free style. One example is to use function composition for some things (e.g. the argument to map or filter), but specify the rest. For instance, take this contrived example:

rejectMapping :: (a -> Bool) -> (a -> b) -> [a] -> [b]
rejectMapping p f = map f . filter (not . p)

这部分是免费的( not)。例如,p ,并且我们没有提供最后一个参数),但是有一部分是满的(存在 p f )。

This is partly point-free (not . p, for instance, and we left off the final argument), but partly point-full (the existence of p and f).

这篇关于从函数应用到函数组合的Haskell类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆