I’m trying to write a brainfuck interpreter in Haskell as an exercise/fun project, and I’ve run into a little problem.
Brainfuck’s “while loop” structure is just a series of commands stuck inside of brackets. I’m trying to build up the syntax tree in a way that I store operators inside loops inside of the [ data constructor.
This is how the data declaration for the commands and syntax “tree” look at the moment:
data Operator = Plus
| Minus
| RShift
| LShift
| Dot
| Comma
| SBracket [Operator]
| EBracket
deriving (Show, Eq)
type STree = [Operator]
What I’m trying to do is take a String of commands like "+><[.>]" and parse it into an STree that looks like this:
[Plus, RShift, LShift, SBracket [Dot, RShift], EBracket]
So far, I’m only able to get a one-dimensional list out of the String, because I’m not sure how to check if the head of the list is a SBracket in order to put new operators in it’s operator list instead of at the head of the main list.
Here’s the function I’m using to do the parsing:
matchChar :: Char -> Maybe Operator
matchChar c = case c of
'+' -> Just Plus
'-' -> Just Minus
'>' -> Just RShift
'<' -> Just LShift
'.' -> Just Dot
',' -> Just Comma
'[' -> Just (SBracket [])
']' -> Just EBracket
_ -> Nothing
getChars :: [Char] -> STree
getChars str = foldr toOp [] str
where
toOp x acc = case matchChar x of
Just a -> a:acc
Nothing -> acc
What I’d like to be able to do is check if head acc is an SBracket instance, and if so, instead of prepending the new Operator to the list, prepend it to SBracket‘s Operator list.
I’ve tried pattern matching (toOp x ((SBracket list):xs) = ...) as well as trying to explicitly check the head of the list (if head acc == SBracket ...), but neither of these things work properly.
Any help would be great!
First off, I’d redefine
SBracket [Operator]as justBracket STreeand get rid ofEBracket. Then I’d change your parser to keep track of both the “current STree” as well as a list of parents. Every time you encounter a bracket, you push the current tree onto your parent list and create a new tree. And when you encounter an end bracket, you take your current tree, wrap it with theBracketconstructor, pop off your first parent, add the bracket to the end of that and make that your current tree.Here’s a wholly untested (don’t have ghc on this comp) version that may or may not work: