Skip to content

Instantly share code, notes, and snippets.

@glowcoil
Forked from devyn/bfLike.hs
Created May 30, 2010 02:32
Show Gist options
  • Save glowcoil/418723 to your computer and use it in GitHub Desktop.
Save glowcoil/418723 to your computer and use it in GitHub Desktop.
module BFLike
(run, interpret, tobc, eval) where
import Data.Char
qqq :: (a, b, c) -> d -> (a, b, c, d)
qqq (a, b, c) d = (a, b, c, d)
run' :: ([Char], [Int], Int) -> Int -> ([Char], [Int], Int)
run' (value, state, ptr) inst =
case inst of
'+' -> (value, (take ptr state) ++ [(state !! ptr) + 1] ++ (drop (ptr + 1) state), ptr)
'-' -> (value, (take ptr state) ++ [(state !! ptr) - 1] ++ (drop (ptr + 1) state), ptr)
'>' -> (value, if length state == ptr + 1 then state ++ [0] else state, ptr + 1)
'<' -> (value, state, ptr - 1)
'.' -> (value ++ [chr $ state !! ptr], state, ptr)
while :: ([Char], [Int], Int, (Bool, [Int])) -> ([Char], [Int], Int, (Bool, [Int]))
while (value, state, ptr, rc) =
if state' !! ptr' < 1
then (value', state', ptr', (False, []))
else while (value', state', ptr', rc)
where (value', state', ptr', rc') = foldl run (value, state, ptr, (False, [])) (snd rc)
run :: ([Char], [Int], Int, (Bool, [Int])) -> Int -> ([Char], [Int], Int, (Bool, [Int]))
run (value, state, ptr, rc) inst =
if fst rc
then
case inst of
'[' -> while (value, state, ptr, (False, snd rc))
_ -> (value, state, ptr, (True, (snd rc) ++ [inst]))
else
case inst of
']' -> (value, state, ptr, (True, []))
_ -> qqq (run' (value, state, ptr) inst) rc
interpret :: [Int] -> [Char]
interpret l = value where (value, state, ptr, rc) = foldl run ([], [0], 0, (False, [])) l
eval :: [Char] -> [Char]
eval = interpret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment