[英]Why does Haskell's “flip id” has this type?
I'm curious about the expression flip id
(It's not homework: I found it in the getOpt
documentation). 我很好奇表达
flip id
(这不是作业:我在getOpt
文档中找到它)。
I wonder why it has this type: 我想知道它为什么有这种类型:
Prelude> :t (flip id)
(flip id) :: b -> (b -> c) -> c
For example, (flip id) 5 (+6)
gives 11
. 例如,
(flip id) 5 (+6)
给出11
。
I know why id (+6) 5
gives 11, but I don't "get" the flip id
thing. 我知道为什么
id (+6) 5
给出了11,但我没有“得到” flip id
东西。
I tried to figure this out myself using pen and paper but couldn't. 我试图用笔和纸来解决这个问题但不能。 Could anybody please explain this to me?
有人可以向我解释一下吗? I mean, how does
flip id
come to have the type b -> (b -> c) -> c
? 我的意思是,
flip id
是如何得到类型b -> (b -> c) -> c
?
The id
function has this type: id
函数具有以下类型:
id :: a -> a
You get an instance of this type, when you replace a
by a -> b
: 当你用
a -> b
替换a
时,你会得到这种类型的实例:
id :: (a -> b) -> (a -> b)
which, because of currying, is the same as: 由于currying,它与以下相同:
id :: (a -> b) -> a -> b
Now apply flip
to this and you get: 现在应用
flip
到这个,你得到:
flip id :: a -> (a -> b) -> b
In the case of id (+)
the instance is: 在
id (+)
的情况下,实例是:
id :: (Num a) => (a -> a) -> (a -> a)
Now flip id
gives you: 现在
flip id
给你:
flip id :: (Num a) => a -> (a -> a) -> a
Side note: This also shows you how ($)
is the same as id
, just with a more restricted type: 附注:这也向您展示了如何
($)
与id
相同,只是使用更受限制的类型:
($) :: (a -> b) -> a -> b
($) f x = f x
-- unpoint:
($) f = f
-- hence:
($) = id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.