Skip to content

Instantly share code, notes, and snippets.

@YoEight
Created July 5, 2012 13:33
Show Gist options
  • Save YoEight/3053678 to your computer and use it in GitHub Desktop.
Save YoEight/3053678 to your computer and use it in GitHub Desktop.
Dataflow programming homework
module Dataflow where
import Data.List
newtype Id a = Id { unId :: a }
class Comonad f where
counit :: f a -> a
cobind :: (f a -> b) -> f a -> f b
cmap :: Comonad f => (a -> b) -> f a -> f b
cmap f = cobind (f . counit)
instance Comonad Id where
counit = unId
cobind f m = Id (f m)
data Prod e a = a :&: e
instance Comonad (Prod e) where
counit (a :&: _) = a
cobind f r@(_ :&: e) = (f r) :&: e
askP :: Prod e a -> e
askP (_ :&: e) = e
localP :: (e -> e) -> Prod e a -> Prod e a
localP f (a :&: e) = a :&: f e
data Stream a = a :< Stream a
instance Comonad Stream where
counit (a :< _) = a
cobind f r@(_ :< xs) = (f r) :< cobind f xs
nextS :: Stream a -> Stream a
nextS (_ :< xs) = xs
newtype CoKleisli f a b = CoKleisli (f a -> b)
pair :: (a -> b) -> (a -> c) -> a -> (b, c)
pair f g x = (f x, g x)
class Arrow f where
pure :: (a -> b) -> f a b
(>>>) :: f a b -> f b c -> f a c
first :: f a b -> f (a, e) (b, e)
instance Comonad w => Arrow (CoKleisli w) where
pure f = CoKleisli (counit . cmap f)
(CoKleisli f) >>> (CoKleisli g) = CoKleisli (g . cobind f)
first (CoKleisli k) = CoKleisli (pair (k . cmap fst) (snd . counit))
str2fun :: Stream a -> Int -> a
str2fun (a :< _) 0 = a
str2fun (_ :< as) i = str2fun as (i - 1)
fun2str :: (Int -> a) -> Stream a
fun2str k = fun2str' k 0 where
fun2str' k i = k i :< fun2str' k (i + 1)
data FunArg s a = (s -> a) :# s
instance Comonad (FunArg s) where
counit (f :# s) = f s
cobind k (f :# s) = (\s' -> k (f :# s')) :# s
runFA :: (FunArg Int a -> b) -> Stream a -> Stream b
runFA k as = runFA' k (str2fun as :# 0) where
runFA' k r@(f :# i) = k r :< runFA' k (f :# (i + 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment