Convert one complete string to int and words as interpreter in Haskell

I am trying to write a Forth interpreter in Haskell. There are many sub-processes and categories for this, however I am trying to follow the most basic steps and I have been doing this for a while in different approaches. The simple input case I'm trying to get to is "25 12 +" -> [37]

. I'm not worried about lists in Forth deviating from Haskell, but I want to try and expand on the extensibility of the input string in the future, so I use Maybe

it as if there is a bug, I'll just do Nothing

.

I first tried to break the input string into a list of "words" using the Prelude function words

. From there, I used the Prelude function reads

to turn it into a list of tuples (Int,String)

. So this works fine until I get a "word" command like char +

in the sample problem.

So how can I parse / interpret the command line for something I can use?
Create a new data structure that has all Forth commands or special characters? (assuming this, how do I convert it from string format to this data type?)

Anything else needed, just ask. I am grateful for the help with this.

+3


source to share


1 answer


read

is essentially a very simple string parser. Instead of adapting it, you may need to learn how to use a parser combinator library like Parsec .

There are many different tutorials out there about parser combinators, so you probably need to read a little before they click. However, the first example in this tutorial is pretty closely related to your problem.

import Text.Parsec
import Text.Parsec.String

play :: String -> Either ParseError Integer
play s = parse pmain "parameter" s

pmain :: Parser Integer
pmain = do
  x <- pnum `chainl1` pplus
  eof
  return x

pnum = read `fmap` many1 digit

pplus = char '+' >> return (+)

      

This is a simple parser that evaluates arbitrarily long lists:



*Main> play "1+2+3+4+5"
Right 15

      

It also generates useful parsing errors:

*Main> play "1+2+3+4+5~"
Left "parameter" (line 1, column 10):
    unexpected '~'
    expecting digit, "+" or end of input

      

If you can understand this simple parser, you should be able to figure out how to adapt it to your specific problem (by referring to the list of generic combinators in the documentation forText.Parsec.Combinator

). It will take a little longer at first than when used read

, but using an appropriate parsing library will make it much easier to achieve the ultimate goal of parsing a Forth grammar.

+2


source







All Articles