Skip to content

Instantly share code, notes, and snippets.

@yashigani
Created March 18, 2014 13:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yashigani/9620236 to your computer and use it in GitHub Desktop.
Save yashigani/9620236 to your computer and use it in GitHub Desktop.
Brainfuck on Haskell(only Hello, world...)
helloworld = "+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+."
type Code = (String, String)
type Pointer = ([Int], [Int], [Int])
parse :: Code -> Pointer -> Pointer
parse ([], _) p = p
parse ('>':xs, bs) p = parse (xs, '>':bs) $ incrementP p
parse ('<':xs, bs) p = parse (xs, '<':bs) $ decrementP p
parse ('+':xs, bs) p = parse (xs, '+':bs) $ increment p
parse ('-':xs, bs) p = parse (xs, '-':bs) $ decrement p
parse ('.':xs, bs) p = parse (xs, '.':bs) $ output p
parse ('[':xs, bs) p = parse (xs, '[':bs) p
parse (']':xs, bs) p = parse (back p (']':xs, bs)) p
incrementP :: Pointer -> Pointer
incrementP (x:xs, bs, buf) = (xs, x:bs, buf)
decrementP :: Pointer -> Pointer
decrementP (xs, b:bs, buf) = (b:xs, bs, buf)
increment :: Pointer -> Pointer
increment (x:xs, bs, buf) = (x+1:xs, bs, buf)
decrement :: Pointer -> Pointer
decrement (x:xs, bs, buf) = (x-1:xs, bs, buf)
output :: Pointer -> Pointer
output (x:xs, bs, buf) = (x:xs, bs, x:buf)
back :: Pointer -> Code -> Code
back (p:_, _, _) (c:cs, bs) = case p of
0 -> (cs, c:bs)
otherwise -> back' (c:cs, bs)
back' :: Code -> Code
back' (xs, '[':bs) = (xs, '[':bs)
back' (xs, b:bs) = back' (b:xs, bs)
main = putStrLn . reverse $ map toEnum buf where (_, _, buf) = parse (helloworld, "") (repeat 0, [], [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment