Skip to content

Instantly share code, notes, and snippets.

@nvanderw
Last active December 24, 2015 01:29
Show Gist options
  • Save nvanderw/6724570 to your computer and use it in GitHub Desktop.
Save nvanderw/6724570 to your computer and use it in GitHub Desktop.
Statically-typed stack effects
module Stack where
import Control.Arrow
class List a
-- Use pairs to represent a cons list which can be statically checked
instance List ()
instance List b => List (a, b)
safeHead :: List b => (a, b) -> a
safeHead = fst
safeTail :: List b => (a, b) -> b
safeTail = snd
-- Given an element, creates a stack effect which pushes it
push :: List b => a -> b -> (a, b)
push = (,)
-- Lifts a 2-argument function to work on stacks
bop :: List l => (a -> b -> c) -> (b, (a, l)) -> (c, l)
bop f (x, (y, z)) = (f y x, z)
swap :: List c => (a, (b, c)) -> (b, (a, c))
swap (x, (y, z)) = (y, (x, z))
main :: IO ()
main = print $ push 1 >>>
push 2 >>>
swap >>>
push 3 >>>
bop (+) >>>
swap >>>
bop div >>>
push "Hello, " >>>
push "world!" >>>
bop (++) $ ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment