Skip to content

Instantly share code, notes, and snippets.

@YoEight
Last active December 13, 2015 22:48
Show Gist options
  • Save YoEight/4986680 to your computer and use it in GitHub Desktop.
Save YoEight/4986680 to your computer and use it in GitHub Desktop.
{-# LANGUAGE RankNTypes #-}
module Fun where
import Data.Monoid
-- Warm up
-- negate 1 = -1
negateCPS :: Int -> (Int -> r) -> r
negateCPS = error "todo"
-- sum 2 2 = 4
sumCPS :: Int -> Int -> (Int -> r) -> r
sumCPS = error "todo"
-- foo 2 2 = sum (negate 2) (negate 2)
-- use negateCPS and sumCPS
fooCPS :: Int -> Int -> (Int -> r) -> r
fooCPS = error "todo"
type Option a = forall r. (a -> r) -> r -> r
mapOption :: (a -> b) -> Option a -> Option b
mapOption = error "todo"
appendOption :: Monoid a => Option a -> Option a -> Option a
appendOption = error "todo"
apOption :: Option (a -> b) -> Option a -> Option b
apOption = error "todo"
bindOption :: (a -> Option b) -> Option a -> Option b
bindOption = error "todo"
foldMapOption :: Monoid m => (a -> m) -> Option a -> m
foldMapOption = error "todo"
negateOption :: Option Int -> Option Int
negateOption = error "todo"
sumOption :: Option Int -> Option Int -> Option Int
sumOption = error "todo"
fooOption :: Option Int -> Option Int -> Option Int
fooOption = error "todo"
{-# LANGUAGE RankNTypes #-}
module FunResponse where
import Data.Monoid
-- Warm up
-- negate 1 = -1
negateCPS :: Int -> (Int -> r) -> r
negateCPS x k = k (negate x)
-- sum 2 2 = 4
sumCPS :: Int -> Int -> (Int -> r) -> r
sumCPS x y k = k (x + y)
-- foo 2 2 = sum (negate 2) (negate 2)
-- use negateCPS and sumCPS
fooCPS :: Int -> Int -> (Int -> r) -> r
fooCPS x y k =
sumCPS x y $ \s ->
negateCPS s k
type Option a = forall r. (a -> r) -> r -> r
mapOption :: (a -> b) -> Option a -> Option b
mapOption f k = \s -> k (s . f)
appendOption :: Monoid a => Option a -> Option a -> Option a
appendOption k k' = \s n -> k (\a -> k' (\a' -> s (a <> a')) n) n
apOption :: Option (a -> b) -> Option a -> Option b
apOption kf k = \s n -> kf (\f -> k (s . f) n) n
bindOption :: (a -> Option b) -> Option a -> Option b
bindOption f k = \s n -> k (\a -> (f a) s n) n
foldMapOption :: Monoid m => (a -> m) -> Option a -> m
foldMapOption f k = k f mempty
negateOption :: Option Int -> Option Int
negateOption = mapOption negate
sumOption :: Option Int -> Option Int -> Option Int
sumOption o o' = apOption (mapOption (+) o) o'
fooOption :: Option Int -> Option Int -> Option Int
fooOption o o' = mapOption negate (sumOption o o')
some :: a -> Option a
some a = \s _ -> s a
none :: Option a
none = \_ n -> n
display :: Show a => Option a -> String
display k = k (\a -> "Some(" ++ (show a) ++ ")") "None"
test1 = display $ fooOption (some 2) (some 3)
test2 = display $ fooOption (some 2) none
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment