Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell for defining a programming language

Tags:

haskell

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

like image 280
user997112 Avatar asked Oct 27 '25 23:10

user997112


2 Answers

There are a couple of common steps to creating a programming language (there are others, of course):

  • parse the program text into a syntax tree
  • walk the syntax tree, doing something with it (interpreting, compiling, collecting statistics)

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")
like image 180
Matt Fenwick Avatar answered Oct 30 '25 09:10

Matt Fenwick


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
like image 35
Zopa Avatar answered Oct 30 '25 07:10

Zopa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!