I have googled about trying to find a simple example of Haskell being used to define a simple language but to no avail.
I did find this post on stackoverflow giving a similar example, but when i implemented it, it didn't appear to work:
Haskell - How to best to represent a programming language's grammar?
an example expression in this language would be:
if true then x else (if false then y else true) Your Haskell data type would look something like this:
data Expr = Var String
| Lit Bool
| If Expr Expr Expr
however, when i entered if true then x else (if false then y else true) into the console as input, it complained about "x" not being interpretable. It also didn't like true and false.
EDIT: I did derive "show" also, at the end
There are a couple of common steps to creating a programming language (there are others, of course):
The data Expr you've shown would be part of a syntax tree. The if true then ... is program text. You need some way to get from text to tree: you need a parser.
Or, you can use Haskell as your parser, and write the syntax tree as Haskell code:
If True "it's true!" (If False "uh-oh" "it's false")
Parsec has extensive programming-language-focused tools. So that's a great place to get started.
It may take some time to wrap your head around the distinction between two things:
Your programming language as text saved in a file.
The representation, in Haskell, of that language.
That's why you need the Lit True and not just true. true is the text in your programming language. Lit True is the Haskell representation. Linking the two is what a parser is for.
To answer another of your questions in comments, a basic solution of the "chair desk" problem is this:
import Text.Parsec
data ProgrammableFurniture = ChairDesk
| CouchCoffeeTable
--a parser for the text "chair desk"
chairDesk = do string "chair"
char ' '
string "desk" <?> "Chair must be followed by desk!"
return ChairDesk
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With