Skip to content

Instantly share code, notes, and snippets.

@5outh
5outh / Comonad.hs
Created January 7, 2013 21:34
Comonad
class (Functor w) => Comonad w where
coreturn :: w a -> a
cojoin :: w a -> w (w a)
(=>>) :: w a -> (w a -> b) -> w b
data Tree a = Node a [Tree a] | Leaf a deriving (Show, Eq)
instance Functor Tree where
fmap f (Leaf a) = Leaf $ f a
fmap f (Node a b) = Node (f a) (map (fmap f) b)
instance Comonad Tree where
coreturn (Leaf a) = a
coreturn (Node a _) = a
cojoin l@(Leaf a) = Leaf l
cojoin n@(Node a b) = Node n (map cojoin b)
x =>> f = fmap f $ cojoin x
@5outh
5outh / shortest.hs
Last active December 10, 2015 20:28
shortest :: (Num a, Ord a) => Tree a -> a
shortest (Leaf x) = x
shortest (Node x xs) = x + (minimum $ map shortest xs)
minimumDist = trip =>> shortest
@5outh
5outh / Simplify.hs
Last active December 16, 2015 20:10
simplify function
simplify :: (Num a, Eq a, Floating a) => Expr a -> Expr a
simplify (Const a :+: Const b) = Const (a + b)
simplify (a :+: Const 0) = simplify a
simplify (Const 0 :+: a ) = simplify a
simplify (Const a :*: Const b) = Const (a*b)
simplify (a :*: Const 1) = simplify a
simplify (Const 1 :*: a) = simplify a
simplify (a :*: Const 0) = Const 0
simplify (Const 0 :*: a) = Const 0
@5outh
5outh / Expr.hs
Last active December 16, 2015 20:10
Expr type
infixl 4 :+:
infixl 5 :*:, :/:
infixr 6 :^:
data Expr a = Var Char
| Const a
| (Expr a) :+: (Expr a)
| (Expr a) :*: (Expr a)
| (Expr a) :^: (Expr a)
| (Expr a) :/: (Expr a)
@5outh
5outh / derivative.hs
Last active December 16, 2015 20:10
derivative function
derivative :: (Num a) => Expr a -> Expr a
derivative (Var c) = Const 1
derivative (Const x) = Const 0
--product rule (ab' + a'b)
derivative (a :*: b) = (a :*: (derivative b)) :+: (b :*: (derivative a)) -- product rule
--power rule (xa^(x-1) * a')
derivative (a :^: (Const x)) = ((Const x) :*: (a :^: (Const $ x-1))) :*: (derivative a)
derivative (a :+: b) = (derivative a) :+: (derivative b)
-- quotient rule ( (a'b - b'a) / b^2 )
derivative (a :/: b) = ((derivative a :*: b) :+: (negate' (derivative b :*: a)))
@5outh
5outh / negate.hs
Last active December 16, 2015 20:10
negate function for Exprs
negate' :: (Num a) => Expr a -> Expr a
negate' (Var c) = (Const (-1)) :*: (Var c)
negate' (Const a) = Const (-a)
negate' (a :+: b) = (negate' a) :+: (negate' b)
negate' (a :*: b) = (negate' a) :*: b
negate' (a :^: b) = Const (-1) :*: a :^: b
negate' (a :/: b) = (negate' a) :/: b
@5outh
5outh / plugin.hs
Last active November 25, 2016 18:23
mapVar and plugIn functions
mapVar :: (Char -> Expr a) => Expr a -> Expr a
mapVar f (Var d) = f d
mapVar _ (Const a) = Const a
mapVar f (a :+: b) = (mapVar f a) :+: (mapVar f b)
mapVar f (a :*: b) = (mapVar f a) :*: (mapVar f b)
mapVar f (a :^: b) = (mapVar f a) :^: (mapVar f b)
mapVar f (a :/: b) = (mapVar f a) :/: (mapVar f b)
plugIn :: Char -> a -> Expr a -> Expr a
plugIn c val = mapVar (\x -> if x == c then Const val else Var x)