【问题标题】:How to reduce code duplication when dealing with recursive sum types处理递归和类型时如何减少代码重复
【发布时间】:2020-02-14 18:12:20
【问题描述】:

我目前正在为一种编程语言开发一个简单的解释器,我有一个这样的数据类型:

data Expr
  = Variable String
  | Number Int
  | Add [Expr]
  | Sub Expr Expr

我有很多功能可以做一些简单的事情,比如:

-- 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 by a negative number
replaceSubWithAdd :: Expr -> Expr
replaceSubWithAdd = go
  where
    go (Sub x (Number y)) =
      Add [go x, Number (-y)]
    go (Add xs) =
      Add $ map go xs
    go (Sub x y) =
      Sub (go x) (go y)
    go other = other

但是在这些函数中的每一个中,我都必须重复递归调用代码的部分,只需对函数的一部分进行少量更改。有没有任何现有的方法可以更通用地做到这一点?我宁愿不必复制和粘贴这部分:

    go (Add xs) =
      Add $ map go xs
    go (Sub x y) =
      Sub (go x) (go y)
    go other = other

而且每次只更改一个 case,因为像这样复制代码似乎效率低下。

我能想出的唯一解决方案是有一个函数,它首先在整个数据结构上调用一个函数,然后递归地调用这样的结果:

recurseAfter :: (Expr -> Expr) -> Expr -> Expr
recurseAfter f x =
  case f x of
    Add xs ->
      Add $ map (recurseAfter f) xs
    Sub x y ->
      Sub (recurseAfter f x) (recurseAfter f y)
    other -> other

substituteName :: String -> Int -> Expr -> Expr
substituteName name newValue =
  recurseAfter $ \case
    Variable x
      | x == name -> Number newValue
    other -> other

replaceSubWithAdd :: Expr -> Expr
replaceSubWithAdd =
  recurseAfter $ \case
    Sub x (Number y) ->
      Add [x, Number (-y)]
    other -> other

但我觉得可能应该有一种更简单的方法来做到这一点。我错过了什么吗?

【问题讨论】:

  • 制作代码的“提升”版本。在哪里使用决定做什么的参数(函数)。然后你可以通过将函数传递给提升的版本来制作特定的函数。
  • 我认为您的语言可以简化。定义Add :: Expr -> Expr -> Expr 而不是Add :: [Expr] -> Expr,并完全摆脱Sub
  • 我只是把这个定义当作一个简化的版本;虽然这在这种情况下可行,但我还需要能够包含该语言其他部分的表达式列表
  • 比如?大多数(如果不是全部)链式运算符可以简化为嵌套的二元运算符。
  • 我认为你的recurseAfter 是伪装的ana。你可能想看看变形和recursion-schemes。话虽如此,我认为您的最终解决方案尽可能短。切换到官方的recursion-schemes 变形不会节省太多。

标签: haskell functional-programming dry code-duplication recursive-type


【解决方案1】:

恭喜,您刚刚重新发现了变形!​​p>

这是您的代码,经过改写后可以与recursion-schemes 包一起使用。唉,它并没有更短,因为我们需要一些样板来使机器工作。 (可能有一些自动的方法来避免样板,例如使用泛型。我根本不知道。)

下面,您的recurseAfter 被替换为标准的ana

我们首先定义你的递归类型,以及它作为不动点的函子。

{-# LANGUAGE DeriveFunctor, TypeFamilies, LambdaCase #-}
{-# OPTIONS -Wall #-}
module AnaExpr where

import Data.Functor.Foldable

data Expr
  = Variable String
  | Number Int
  | Add [Expr]
  | Sub Expr Expr
  deriving (Show)

data ExprF a
  = VariableF String
  | NumberF Int
  | AddF [a]
  | SubF a a
  deriving (Functor)

然后我们用几个实例将两者连接起来,这样我们就可以将Expr展开成同构的ExprF Expr,然后将其折叠回来。

type instance Base Expr = ExprF
instance Recursive Expr where
   project (Variable s) = VariableF s
   project (Number i) = NumberF i
   project (Add es) = AddF es
   project (Sub e1 e2) = SubF e1 e2
instance Corecursive Expr where
   embed (VariableF s) = Variable s
   embed (NumberF i) = Number i
   embed (AddF es) = Add es
   embed (SubF e1 e2) = Sub e1 e2

最后,我们调整您的原始代码,并添加几个测试。

substituteName :: String -> Int -> Expr -> Expr
substituteName name newValue = ana $ \case
    Variable x | x == name -> NumberF newValue
    other                  -> project other

testSub :: Expr
testSub = substituteName "x" 42 (Add [Add [Variable "x"], Number 0])

replaceSubWithAdd :: Expr -> Expr
replaceSubWithAdd = ana $ \case
    Sub x (Number y) -> AddF [x, Number (-y)]
    other            -> project other

testReplace :: Expr
testReplace = replaceSubWithAdd 
   (Add [Sub (Add [Variable "x", Sub (Variable "y") (Number 34)]) (Number 10), Number 4])

另一种方法是只定义ExprF a,然后派生type Expr = Fix ExprF。这节省了上面的一些样板文件(例如两个实例),代价是必须使用 Fix (VariableF ...) 而不是 Variable ...,以及其他构造函数的类似内容。

使用模式同义词可以进一步缓解这种情况(不过,以更多样板为代价)。


更新:我终于找到了自动魔术工具,使用模板 Haskell。这使得整个代码相当短。请注意,ExprF 函子和上面的两个实例仍然存在于底层,我们仍然必须使用它们。我们只省去了手动定义它们的麻烦,但仅此一项就节省了很多精力。

{-# LANGUAGE DeriveFunctor, DeriveTraversable, TypeFamilies, LambdaCase, TemplateHaskell #-}
{-# OPTIONS -Wall #-}
module AnaExpr where

import Data.Functor.Foldable
import Data.Functor.Foldable.TH

data Expr
  = Variable String
  | Number Int
  | Add [Expr]
  | Sub Expr Expr
  deriving (Show)

makeBaseFunctor ''Expr

substituteName :: String -> Int -> Expr -> Expr
substituteName name newValue = ana $ \case
    Variable x | x == name -> NumberF newValue
    other                  -> project other

testSub :: Expr
testSub = substituteName "x" 42 (Add [Add [Variable "x"], Number 0])

replaceSubWithAdd :: Expr -> Expr
replaceSubWithAdd = ana $ \case
    Sub x (Number y) -> AddF [x, Number (-y)]
    other            -> project other

testReplace :: Expr
testReplace = replaceSubWithAdd 
   (Add [Sub (Add [Variable "x", Sub (Variable "y") (Number 34)]) (Number 10), Number 4])

【讨论】:

  • 你真的必须明确定义Expr,而不是像type Expr = Fix ExprF这样的东西吗?
  • @chepner 我简要地提到了它作为替代方案。对所有东西都必须使用双重构造函数有点不方便:Fix + 真正的构造函数。 IMO,将最后一种方法与 TH 自动化结合使用会更好。
【解决方案2】:

作为替代方法,这也是uniplate 包的典型用例。它可以使用 Data.Data 泛型而不是 Template Haskell 来生成样板,因此如果您为 Expr 派生 Data 实例:

import Data.Data

data Expr
  = Variable String
  | Number Int
  | Add [Expr]
  | Sub Expr Expr
  deriving (Show, Data)

然后来自Data.Generics.Uniplate.Datatransform 函数递归地将函数应用于每个嵌套的Expr

import Data.Generics.Uniplate.Data

substituteName :: String -> Int -> Expr -> Expr
substituteName name newValue = transform f
  where f (Variable x) | x == name = Number newValue
        f other = other

replaceSubWithAdd :: Expr -> Expr
replaceSubWithAdd = transform f
  where f (Sub x (Number y)) = Add [x, Number (-y)]
        f other = other

请注意,特别是在replaceSubWithAdd 中,函数f 是为了执行非递归替换而编写的; transform 使其在 x :: Expr 中递归,因此它对辅助函数的作用与 @chi 的答案中的 ana 相同:

> substituteName "x" 42 (Add [Add [Variable "x"], Number 0])
Add [Add [Number 42],Number 0]
> replaceSubWithAdd (Add [Sub (Add [Variable "x", 
                     Sub (Variable "y") (Number 34)]) (Number 10), Number 4])
Add [Add [Add [Variable "x",Add [Variable "y",Number (-34)]],Number (-10)],Number 4]
> 

这不比@chi 的 Template Haskell 解决方案短。一个潜在的优势是uniplate 提供了一些可能有用的附加功能。例如,如果您使用descend 代替transform,它只会转换立即 孩子,这可以让您控制递归发生的位置,或者您可以使用rewrite 重新变换变换的结果,直到达到一个固定点。一个潜在的缺点是“变形”听起来比“单板”更酷。

完整程序:

{-# LANGUAGE DeriveDataTypeable #-}

import Data.Data                     -- in base
import Data.Generics.Uniplate.Data   -- package uniplate

data Expr
  = Variable String
  | Number Int
  | Add [Expr]
  | Sub Expr Expr
  deriving (Show, Data)

substituteName :: String -> Int -> Expr -> Expr
substituteName name newValue = transform f
  where f (Variable x) | x == name = Number newValue
        f other = other

replaceSubWithAdd :: Expr -> Expr
replaceSubWithAdd = transform f
  where f (Sub x (Number y)) = Add [x, Number (-y)]
        f other = other

replaceSubWithAdd1 :: Expr -> Expr
replaceSubWithAdd1 = descend f
  where f (Sub x (Number y)) = Add [x, Number (-y)]
        f other = other

main = do
  print $ substituteName "x" 42 (Add [Add [Variable "x"], Number 0])
  print $ replaceSubWithAdd e
  print $ replaceSubWithAdd1 e
  where e = Add [Sub (Add [Variable "x", Sub (Variable "y") (Number 34)])
                     (Number 10), Number 4]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多