开发者

How does a pair unify with the types of the Arrow functions

Some of the functions for working with Arrows ar开发者_如何学运维e quite handy to use on pairs. But I can't understand how the types of these functions unify with a pair. In general, I find the types of the Arrow related functions to be quite confusing.

For example, we have first :: a b c -> a (b, d) (c, d), which means little to me. But it can be used to, say, increment the first number in a pair:

Prelude Control.Arrow> :t first (+1)
first (+1) :: (Num b) => (b, d) -> (b, d)

And

Prelude Control.Arrow> :t (&&&)
(&&&) :: (Arrow a) => a b c -> a b c' -> a b (c, c')

Prelude Control.Arrow> :t (pred &&& succ)
(pred &&& succ) :: (Enum b) => b -> (b, b)

Could someone please explain how this works?


There is an instance for Arrow (->). So

(&&&) :: (Arrow a) => a b c -> a b c' -> a b (c,c')

has the instantiation

(&&&) :: (->) b c -> (->) b c' -> (->) b (c,c')

or, written in more conventional notation,

(&&&) :: (b -> c) -> (b -> c') -> (b -> (c,c'))

The rest should follow from that.

I use the arrow functions (especially (***) and (&&&)) all the time on the (->) instance. My usage of those combinators for any other instance of Arrow is very rare. So whenever you see a b c, think "(generalized) function from b to c", which works for regular functions too.


The first arrow takes a normal arrow, and changes it to perform its operation on the first element in a tuple and outputs the result as an arrow

a b c -> a (b, d) (c, d)

a b c -- is the input arrow, an operation that maps type b to c
a (b, d) (c, d) -- is the output arrow, an operation that maps a tuple (b, d) to (c, d)

it uses d as a dummy for the unknown second type in the tuple

&&& takes two arrows that take the same input and creates an arrow that takes that input, duplicates it into a tuple and runs one of the arrows on each part of the tuple, returning the altered tuple.

for some solid tutorial, check out: http://www.vex.net/~trebla/haskell/hxt-arrow/lesson-0.xhtml


I did this blog post not long ago about how to use Arrow functions on pure functions

http://blog.romanandreg.com/post/2755301358/on-how-haskells-are-just-might-just-be-function

I try to cover all the basic Arrow methods in a really simple and detailed fashion.

Cheers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜