Execute Brain****/Haskell: Difference between revisions
m
Fixed syntax highlighting.
m (RCBF (Haskell) moved to RCBF/Haskell: MW has page hierarchy support.) |
m (Fixed syntax highlighting.) |
||
(10 intermediate revisions by 8 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).
In functional style, ''run'' interprets a Brainfuck program as a function from an Integer list (inputs) to an Integer list (outputs).
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="haskell">module BF where
exec :: (String, String) -> ([Integer], [Integer]) -> [Integer] -> [Integer]▼
▲ exec p@(_,'[':_) d@(_,0:_) cs = exec (matchRight $ moveRight $ p) d cs
▲ exec p@(_,'[':_) d cs = exec (moveRight p) d cs
▲ exec p@(_,']':_) d@(_,0:_) cs = exec (moveRight p) d cs
▲ exec p@(_,']':_) d cs = exec (matchLeft $ moveLeft $ p) d cs
</syntaxhighlight>(This version compiles with GHC and will run if loaded into ghci using ':load BF')
▲ run s = exec ([],s) ([0],[0])
▲ dialog :: String -> IO ()
▲ dialog s = mapM_ print $ run s $ repeat (unsafePerformIO readLn)
Example session:
<pre>
: *Main> dialog ",[>+<-].>."
: ''5''
: 0
: 5
</pre>
|