-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluate.hs
More file actions
41 lines (33 loc) · 1.27 KB
/
Evaluate.hs
File metadata and controls
41 lines (33 loc) · 1.27 KB
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
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GADTs #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module Evaluate where
import Validate (Index (..))
import qualified Validate as Validated
data Value t where
Boolean :: Bool -> Value Bool
Integer :: Integer -> Value Integer
Closure :: (Value t -> Value t') -> Value (t -> t')
instance Show (Value t) where
show = \case
Boolean b -> show b
Integer i -> show i
Closure _ -> "<closure>"
data VariableEnvironment env where
Empty :: VariableEnvironment '[]
Cons :: Value t -> VariableEnvironment env -> VariableEnvironment (t : env)
evaluate :: Validated.Expression '[] t -> Value t
evaluate expr = go Empty expr
where
go :: VariableEnvironment env -> Validated.Expression env t -> Value t
go env = \case
Validated.BooleanLiteral b -> Boolean b
Validated.IntegerLiteral i -> Integer i
Validated.Abstraction body -> Closure $ \arg -> go (Cons arg env) body
Validated.Application fun arg -> let Closure f = go env fun in f (go env arg)
Validated.Variable idx -> get idx env
get :: Index env t -> VariableEnvironment env -> Value t
get Zero (Cons val _) = val
get (Succ idx) (Cons _ env) = get idx env