Execute Brain****/Haskell: Difference between revisions
m
Fixed syntax highlighting.
No edit summary |
m (Fixed syntax highlighting.) |
||
(4 intermediate revisions by 4 users not shown) | |||
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
Quick implementation of a [[Brainfuck]] interpreter in [[Haskell]].
Pairs of lists are used to implement both the two-side infinite band of cells, and the program storage. This means that it can also work on infinite Brainfuck programs (which could be generated lazily).
Line 8:
A more efficient implementation could for example only admit well-bracketed brainfuck programs, and parse bracket blocks first, to replace the ''matchLeft'' and ''matchRight'' which need linear time.
<syntaxhighlight lang
moveLeft (x:l,r) = (l,x:r)
moveRight (l,x:r) = (x:l,r)
Line 31 ⟶ 33:
exec p@(_,'<':_) d cs = exec (moveRight p) (pad $ moveLeft $ d) cs
exec p@(_,'+':_) d cs = exec (moveRight p) (modify (+ 1) d) cs
exec p@(_,'-':_) d cs = exec (moveRight p) (modify (
exec p@(_,',':_) d (c:cs) = exec (moveRight p) (modify (const c) d) cs
exec p@(_,'.':_) d@(_,x:_) cs = x : exec (moveRight p) d cs
Line 44 ⟶ 46:
dialog :: String -> IO ()
dialog s = mapM_ print . run s . map read . lines =<< getContents
</syntaxhighlight>(This version compiles with GHC and will run if loaded into ghci using ':load BF')
Example session:
|