小编Sco*_*ott的帖子

处理递归和类型时如何减少代码重复

我目前正在为一种编程语言开发一个简单的解释器,并且我的数据类型如下:

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)

haskell functional-programming

48
推荐指数
2
解决办法
6125
查看次数

标签 统计

functional-programming ×1

haskell ×1