From: ocaml@optimojoe.com
To: caml-list@inria.fr
Subject: Encoding an extensible parse tree and subtyping within OCaml
Date: Wed, 03 Mar 2010 18:11:33 +0100 [thread overview]
Message-ID: <1267636293.17362.1362924937@webmail.messagingengine.com> (raw)
Hi,
Is there a good way to encode a parse tree in OCaml where the terms
in the parse tree can be extended later? Essentially, it would be
nice not to represent the trees for different grammars separately
so that code for type checking, evaluation, or pretty printing can
be reused. I'm including one possible solution below that seems to
work reasonably well, but I'm interested in whether this can be
done better. The two things that would be nice to improve upon the
example are preventing statements such as "bad" where improper
trees are created. It would also be nice to have the OCaml type
system flag an error on the line with "`Junk". Though, it does give
a warning now.
Joe
type base = [`Int of int];;
type 'a basic= [base | `Add of 'a*'a | `Sub of 'a*'a ];;
type 'a ext= ['a basic | `Mul of 'a*'a];;
type basic'=('a basic as 'a) basic;;
type ext'=('a ext as 'a) ext;;
let (x:'a basic)=`Add (`Int 1,`Int 2);;
let (y:'a ext)=`Mul (x,`Int 3);;
let (z:'a basic)=`Add (`Int 3,x);;
let w=`Add (`Mul (`Int 1,`Int 2),`Int 3);;
let (bad:'a basic)=`Add (1,2);;
let pp x=
let rec pp (x:ext') =
match x with
| `Int x-> Printf.printf "%d" x
| `Add (x,y) ->
pp x; Printf.printf "+"; pp y
| `Sub (x,y) ->
pp x; Printf.printf "-"; pp y
| `Mul (x,y) ->
pp x; Printf.printf "*"; pp y
| `Junk -> Printf.printf "BAD!"
in
pp (x :> ext');Printf.printf "\n"
;;
let eval x=
let rec eval (x:basic')=
match x with
| `Int x -> x
| `Add (x,y) -> (eval x) + (eval y)
| `Sub (x,y) -> (eval x) - (eval y)
in
eval (x:>basic')
;;
next reply other threads:[~2010-03-03 17:11 UTC|newest]
Thread overview: 2+ messages / expand[flat|nested] mbox.gz Atom feed top
2010-03-03 17:11 ocaml [this message]
2010-03-03 17:47 ` [Caml-list] " Markus Mottl
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=1267636293.17362.1362924937@webmail.messagingengine.com \
--to=ocaml@optimojoe.com \
--cc=caml-list@inria.fr \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox