跳轉到內容

Haskell/解決方案/理解箭頭

來自華夏公益教科書

← 返回理解箭頭

箭頭的口袋指南

[編輯 | 編輯來源]

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)
華夏公益教科書