-
Notifications
You must be signed in to change notification settings - Fork 5
/
Example.sml
53 lines (43 loc) · 1.52 KB
/
Example.sml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
structure Example =
struct
(*
Small demonstration of how to use Wpp and the utilities.
An often occurring challenge is to format if-then-else nicely, so that
is mainly what we'll demonstrate,
*)
local
structure U = Utility
val $ = U.$
val ^+^ = U.^+^
infix ^+^
in
datatype Ast = Var of string
| Lit of int
| Opr of Ast * string * Ast
| Cond of Ast * Ast * Ast
fun toDoc ast =
case ast of
Var v => $v
| Lit n => Wpp.int n
| Opr(x, opr, y) => U.bin toDoc ($opr) (x, y)
| Cond(test, pos, neg) =>
Wpp.group (U.spread [ U.block 2 ($"if" ^+^ toDoc test)
, U.block 2 ($"then" ^+^ toDoc pos)
, U.block 2 ($"else" ^+^ toDoc neg)])
(* AST for `if (x > y) then x+1 else y*z` *)
val maxEx = Cond(Opr(Var"x", ">", Var"y"),
Opr(Var"x", "+", Lit 1),
Opr(Var"y", "*", Var"z"))
val maxDoc = toDoc maxEx
val maxS50 = Wpp.toString 50 maxDoc (* equals "if (x > y) then (x + 1) else (y * z)\n" *)
val maxS30 = Wpp.toString 30 maxDoc (* equals "if (x > y)\nthen (x + 1)\nelse (y * z)\n" *)
val maxS10 = Wpp.toString 10 maxDoc (* equals "if (x > y)\nthen\n (x + 1)\nelse\n (y * z)\n" *)
val nested = Cond(Opr(Var"x", ">", Var"y"),
Opr(Var"x", "+", Lit 1),
maxEx)
val nestDoc = toDoc nested
val nestS50 = Wpp.toString 50 nestDoc
val nestS30 = Wpp.toString 30 nestDoc
val nestS10 = Wpp.toString 10 nestDoc
end
end