问题描述
我很好奇表达式
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”有这种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!