Haskell - 使用实例函数进行模式匹配

时间:2014-01-02 15:34:26

标签: haskell

我想用加号和减号操作实现一个简单的表达式树。

我使用以下函数签名实现了一个“Group”类:

-- type class  Group a ---------------------------------------------------------

class (Eq a, Show a, Read a, Num a) => Group a where 
add :: a -> a -> a
identity :: a 
invers :: a -> a

添加获取两个元素并返回总和(例如4 + 7 = 11),identity是一个特殊元素,使其他元素保持不变(即0因为3 + 0 = 3)并且invers计算元素的反转(例如3的倒数是-3)。

此类的实例适用于integer类型的值,因此它看起来像这样:

-- Group Integer  ----------------------------------------------------------------

instance Group Integer where 
  add x y = x+y
  invers x = -x
  identity = 0

表达式树应包含以下数据元素:

-- expression tree with values having Group property ---------------------------

 data  Expr a = Lit a | Invers (Expr a) | Add (Expr a) (Expr a) deriving (Eq, Read)

Lit构造函数获取某种类型的元素(例如Integer值),Invers获取子表达式,Add获取两个子表达式。

我现在想要实现的是实现一个名为“简化”的函数。它应该基于以下公理简化任何表达式:

x `add` idenity = x
idenity `add` x = x
x `add` (invers x) = identity
(invers x) `add` x = identity

到目前为止我实施的内容如下:

-- simplify --------------------------------------------------------------------

-- simplify simplifies expression trees applying Group laws as follows ---------
--   add x zero = x
--   add zero x = x
--   add x (minus x) = zero 
--   add (minus x) x = zero 

----- Match for any axiom ----
simplify :: (Group a) =>  Expr a -> Expr a
simplify (Add(Lit x) (Invers (Lit y)))  | x == y  = Lit identity
simplify (Invers (Invers (Lit x))) = Lit x
simplify (Invers (Lit identity)) = Lit identity
simplify (Add(Lit x) (Lit identity)) = Lit x
simplify (Add(Lit identity) (Lit x)) = Lit x

----- No axiom found, so call simplify recusively ---- 
simplify (Invers x) = simplify (x) --  x is a sub    expression
simplify (Add x y) = Add (simplify x) (simplify y) -- x and/or y are sub expressions

我的问题是我无法匹配简化函数左侧的“identity”元素。

该行

simplify (Invers (Lit identity)) = Lit identity

相同
simplify (Invers (Lit x)) = Lit x

因为identity是此范围内的任何变量。是否有可能与“组”类的身份功能相匹配?

非常感谢。

1 个答案:

答案 0 :(得分:0)

为什么不简化(反向(点亮x))| x == identity = identity,还是我误解了你的问题? [bennofs]