Skip to content

Instantly share code, notes, and snippets.

@jhusain
Created December 16, 2024 18:09
Show Gist options
  • Save jhusain/c1495ff445ffcf68012617585a4456e6 to your computer and use it in GitHub Desktop.
Save jhusain/c1495ff445ffcf68012617585a4456e6 to your computer and use it in GitHub Desktop.
eval for mini language.roc
Expr : [
Func Str Expr,
Call Expr Expr,
Symbol Str,
Add Expr Expr,
Const I32,
]
eval: Expr, Dict Str Expr -> Result Expr [ExpectedFunction, SymbolNotFound Str, ExpectedI32]
eval = \ast, scope ->
when ast is
Func _ _ as f -> Ok f
Call fn arg ->
when eval? fn scope is
Func name expr ->
eval expr (Dict.insert scope name arg)
_ -> Err ExpectedFunction
Symbol name ->
when Dict.get scope name is
Ok lookup -> eval lookup scope
_ -> Err (SymbolNotFound name)
Add left right ->
when (eval? left scope, eval? right scope) is
(Const lhs, Const rhs) -> Ok (Const (lhs + rhs))
_ -> Err ExpectedI32
Const v -> Ok (Const v)
(Add (Const 5) (Const 5))
|> eval (Dict.empty {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment