Last active
July 1, 2022 11:22
-
-
Save conf8o/786118c3178d48dac2657cb5e61004ca to your computer and use it in GitHub Desktop.
AST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Val = | |
| Int of int | |
| Bool of bool | |
type Ope = Add | Mul | Lt | |
type Ast = | |
| Val of Val | |
| Form of Ope * Ast * Ast | |
let exec ope v1 v2 = | |
match ope, v1, v2 with | |
| Add, Int x, Int y -> Int (x + y) | |
| Mul, Int x, Int y -> Int (x * y) | |
| Lt, Int x, Int y -> Bool (x < y) | |
let rec eval = | |
function | |
| Form (ope, left, right) -> | |
let (Val leftVal) = eval left | |
let (Val rightVal) = eval right | |
Val <| exec ope leftVal rightVal | |
| x -> x | |
let form ope a b = Form (ope, a, b) | |
let integer x = Val (Int x) | |
let x = | |
form Add (integer 1) | |
<< form Mul (integer 5) | |
<| form Add (integer 20) (integer 3) | |
let (Val (Bool p)) = form Lt (integer 100) x |> eval | |
stdout.WriteLine p |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data Val = Int Int | Bool Bool deriving Show | |
data Ope = Add | Mul | Lt deriving Show | |
data Ast = Val Val | Form Ope Ast Ast deriving Show | |
form :: Ope -> Val -> Val -> Val | |
form Add (Int x) (Int y) = Int (x + y) | |
form Mul (Int x) (Int y) = Int (x * y) | |
form Lt (Int x) (Int y) = Bool (x < y) | |
red :: Ast -> Ast | |
red (Form ope left right) = | |
let Val leftVal = (red left) | |
Val rightVal = (red right) | |
in Val (form ope leftVal rightVal) | |
red x = x | |
main = do print $ red (Form Lt y x) | |
where | |
x = | |
Form Add (Val (Int 1)) | |
$ Form Mul (Val (Int 5)) | |
$ Form Add (Val (Int 20)) (Val (Int 3)) | |
y = | |
Val (Int 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment