Advertisement
Revolucent

Haskell ArrowReader & ArrowState

Nov 30th, 2020
1,777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE Arrows #-}
  2. {-# LANGUAGE FlexibleInstances #-}
  3. {-# LANGUAGE FunctionalDependencies #-}
  4.  
  5. module Arr where
  6.  
  7. {-
  8.  
  9. As an exercise in learning arrows, I implemented a reader arrow called EA
  10. and a state arrow called S.
  11.  
  12. -}
  13.  
  14. import Prelude hiding ((.), id)
  15. import Control.Category
  16. import Control.Arrow
  17. import qualified Data.Bifunctor as BiF
  18.  
  19. newtype EA r a b = EA { runEA :: r -> a -> b }
  20.  
  21. instance Arrow (EA r) where
  22.   arr f = EA $ const f
  23.   first (EA f) = EA $ BiF.first . f
  24.   second (EA f) = EA $ BiF.second . f
  25.  
  26. instance Category (EA r) where
  27.   id = arr id
  28.   (EA b) . (EA a) = EA $ \r -> b r . a r
  29.  
  30. class Arrow a => ArrowReader r a | a -> r where
  31.   ask :: a () r
  32.  
  33. instance ArrowReader r (EA r) where
  34.   ask = EA const
  35.  
  36. newtype S s a b = S { runS :: s -> a -> (b, s) }
  37.  
  38. evalS :: S s a b -> s -> a -> b
  39. evalS z s a = fst $ runS z s a
  40.  
  41. execS :: S s a b -> s -> a -> s
  42. execS z s a = snd $ runS z s a
  43.  
  44. instance Arrow (S s) where
  45.   arr f = S $ \s a -> (f a, s)
  46.   first (S f) = S $ \s (a, b) -> let (a', s') = f s a in ((a', b), s')
  47.   second (S f) = S $ \s (a, b) -> let (b', s') = f s b in ((a, b'), s')
  48.  
  49. instance Category (S s) where
  50.   id = arr id
  51.   (S b) . (S a) = S $ \s x -> let (a', s') = a s x in b s' a'
  52.  
  53. class Arrow a => ArrowState s a | a -> s where
  54.   get :: a b s
  55.   put :: a s ()
  56.  
  57. modify :: ArrowState s a => a (s -> s) ()
  58. modify = proc f -> do
  59.   s <- get -< ()
  60.   put -< f s
  61.  
  62. instance ArrowState s (S s) where
  63.   get = S $ \s _ -> (s, s)
  64.   put = S $ \_ s -> ((), s)
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement