我目前正在为一种编程语言开发一个简单的解释器,并且我的数据类型如下:
data Expr
= Variable String
| Number Int
| Add [Expr]
| Sub Expr Expr
Run Code Online (Sandbox Code Playgroud)
我有许多函数可以执行简单的操作,例如:
-- Substitute a value for a variable
substituteName :: String -> Int -> Expr -> Expr
substituteName name newValue = go
where
go (Variable x)
| x == name = Number newValue
go (Add xs) =
Add $ map go xs
go (Sub x y) =
Sub (go x) (go y)
go other = other
-- Replace subtraction with a constant with addition …Run Code Online (Sandbox Code Playgroud)