为什么Haskell的“flip id”有这种类型? [英] Why does Haskell's "flip id" has this type?
问题描述
我很好奇表达式 flip id
(这不是作业:我在 getOpt
文档中找到了它)。
我想知道为什么会有这种类型:
Prelude> ; :t(flip id)
(flip id):: b - > (b→c)→> c
例如,(flip id)5(+6) code>给出
11
。
我知道为什么 id(+6) 5
给出11,但我没有得到 flip id
的东西。
<我试图用笔和纸自己弄清楚,但不能。有谁可以向我解释这个吗?我的意思是,
flip flip
如何得到类型 b - > (b→c)→> ?解决方案 id 函数有这样的类型:
id :: a - > a
当您将 a 由 a - > b :
id ::(a - > b) - > (a - > b)
由于currying,它与以下相同:
id ::(a - > b) - > a - > b
现在将翻转
get:
flip id :: a - > (a - > b) - > b
id(+)实例是:
id ::(Num a)=> (a - > a) - > (a - > a)
现在 flip id
给你:
flip id ::(Num a)=> a - > (a - > a) - > a
注意:这也显示了($)
与 id
相同,仅限于更受限制的类型:
($)::(a - > b) - > a - > b
($)fx = fx
- 非点:$ b $ b($)f = f
- 因此:
($)= id
I'm curious about the expression flip id
(It's not homework: I found it in the getOpt
documentation).
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
.
I know why id (+6) 5
gives 11, but I don't "get" the flip id
thing.
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
?
解决方案 The id
function has this type:
id :: a -> a
You get an instance of this type, when you replace a
by a -> b
:
id :: (a -> b) -> (a -> b)
which, because of currying, is the same as:
id :: (a -> b) -> a -> b
Now apply flip
to this and you get:
flip id :: a -> (a -> b) -> b
In the case of id (+)
the instance is:
id :: (Num a) => (a -> a) -> (a -> a)
Now flip id
gives you:
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:
($) :: (a -> b) -> a -> b
($) f x = f x
-- unpoint:
($) f = f
-- hence:
($) = id
这篇关于为什么Haskell的“flip id”有这种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文