Skip to content

Instantly share code, notes, and snippets.

@righ1113
Last active November 15, 2023 23:59
Show Gist options
  • Save righ1113/7805bc5ca88da23d2616a13c6a5ba016 to your computer and use it in GitHub Desktop.
Save righ1113/7805bc5ca88da23d2616a13c6a5ba016 to your computer and use it in GitHub Desktop.
Brainf*ck in Egison
--
-- Brainf*ck
--
-- $ egison 4.1.3
-- > loadFile "bf2.egi"
--
-- Pattern Function
--
def bfLoopPatt := \pat1 => #'[' :: $x :: ~pat1 ++ #(pack [']', x])
--
-- Codes
--
def parse code := parse' code 1 [] where
parse' code mark acc := match code as string with
| [] -> pack $ reverse acc
| #'[' :: $xs -> parse' xs (mark + 1) ((itoc (mark + 48 )) :: '[' :: acc)
| #']' :: $xs -> parse' xs (mark - 1) ((itoc (mark + 48 - 1)) :: ']' :: acc)
| $x :: $xs -> parse' xs mark (x :: acc)
def bf code := do{ run code (take 10 $ repeat1 0, 0, take 10 $ repeat1 0); write "" } where
run code d := match (code, d) as (string, (list integer, integer, list integer)) with
| ([], _ ) -> return d
| ((bfLoopPatt _) ++ $xs, (_, #0, _) ) -> run xs d
| ((bfLoopPatt $x) ++ $xs, _ ) -> run code $ io $ run x d -- loop
| (#'>' :: $xs, ($ls, $c, $rx :: $rs2)) -> run xs (c :: ls, rx, rs2)
| (#'<' :: $xs, ($lx :: $ls2, $c, $rs)) -> run xs (ls2, lx, c :: rs)
| (#'+' :: $xs, ($ls, $c, $rs) ) -> run xs (ls, (c + 1), rs)
| (#'-' :: $xs, ($ls, $c, $rs) ) -> run xs (ls, (c - 1), rs)
| (#'.' :: $xs, (_, $c, _) ) -> do{ write $ pack [itoc c]; run xs d }
| (#',' :: $xs, _ ) -> run xs d -- omitted
| (_ :: $xs, _ ) -> run xs d
--
-- Data
--
-- 1m35s
def hello :=
"++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
--
-- Tests
--
-- $ egison -t bf2.egi
io $ bf $ parse hello
def test5 := matchAll "[1ii[2abc]2xxx[2y[3]3]2df]1ggg" as string with
| (bfLoopPatt $x) ++ $xs -> (x, xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment