If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Saturday, October 12, 2013

Simple example of using a recursive datatype (ML)

datatype exp = Constant of int
| Negate of exp
| Add of exp * exp
| Multiply of exp * exp
fun eval e =
case e of
Constant i => i
| Negate e2 => ~ (eval e2)
| Add(e1,e2) => (eval e1) + (eval e2)
| Multiply(e1,e2) => (eval e1) * (eval e2)
fun max_constant e =
case e of
Constant i => i
| Negate e1 => max_constant e1
| Add(e1,e2) => Int.max(max_constant e1,max_constant e2)
| Multiply(e1,e2) => Int.max(max_constant e1,max_constant e2)
val example_exp = Add (Constant (10+9), Negate (Constant 4))
val result = eval example_exp
val maxconstant = max_constant example_exp
(* output of program
- use "expression.sml";
[opening expression.sml]
datatype exp
= Add of exp * exp | Constant of int | Multiply of exp * exp | Negate of exp
val eval = fn : exp -> int
val max_constant = fn : exp -> int
val example_exp = Add (Constant 19,Negate (Constant 4)) : exp
val result = 15 : int
val maxconstant = 19 : int
val it = () : unit
*)
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment