Jump to content

Haskell/Solutions/Understanding arrows

From Wikibooks, open books for an open world

← Back to Understanding arrows

Pocket guide to Arrow

[edit | edit source]

1.

-- Available from Data.Tuple
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)

second :: Arrow y => y a b -> y (c, a) -> y c b
second f = arr swap >>> first f >>> arr swap

(***) :: Arrow y => y a c -> y b d -> y (a, b) (c, d)
f *** g = first f >>> second g

dup :: a -> (a, a)
dup x = (x, x)

(&&&) :: Arrow y => y a b -> y a c -> y a (b, c)
f &&& g = arr dup >>> f *** g

2.

swapTags :: Either a b -> Either b a
swapTags e = case e of
    Left x  -> Right x
    Right x -> Left x

right :: y a b -> y (Either c a) (Either c b)
right f = arr swapTags >>> left f >>> arr swapTags

3.

liftY2 :: Arrow y => (a -> b -> c) -> y r a -> y r b -> y r c
liftY2 f g h = g &&& h >>> arr (uncurry f)