简体   繁体   English

为什么Haskell的“翻转id”有这种类型?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM