具有数据模式匹配和第二个参数的Haskell函数给出具有不同数量参数的方程

问题描述 投票:0回答:1

在 Haskell 中我有以下数据结构

data Circ = IN String
    | NOT Circ
    | AND Circ Circ
    | OR Circ Circ
    | XOR Circ Circ

我可以像这样对函数进行模式匹配:

size :: Circ -> Int
size (IN _) = 0
..
size (XOR a b) = 1 + (size a) + (size b)

但是当我尝试使用附加参数时:

simulate :: Circ -> [(String, Bool)] -> Bool
simulate (IN a) c = findIn c a
simulate (NOT a) c = not $ simulate a c
simulate (AND a b) c = all (simulate a c) (simulate b c)
simulate (OR a b) c = any (simulate a c) (simulate b c)
simulate (XOR a b) = xor (simulate a c) (simulate b c)

我收到错误“模拟”方程有不同数量的参数。 如何编写一个函数,使模式与带有额外参数的数据结构相匹配?

我尝试重写括号,但在网上找不到任何相关内容。

我希望它将数据结构的值放入某些参数中,并同时接收下一个参数。

提前致谢!

haskell arguments
1个回答
0
投票

这是由于最后一句中缺少

c
造成的:

simulate :: Circ -> [(String, Bool)] -> Bool
simulate (IN a) c = findIn c a
simulate (NOT a) c = not $ simulate a c
simulate (AND a b) c = all (simulate a c) (simulate b c)
simulate (OR a b) c = any (simulate a c) (simulate b c)
simulate (XOR a b) c = xor (simulate a c) (simulate b c)

另一个问题是

all :: Foldable t => (a -> Bool) -> t a -> Bool
函数[Hackage]
any :: Foldable t => (a -> Bool) -> t a -> Bool
函数[Hackage]
使用
Foldable
项,而不是两个参数;所以:

simulate :: Circ -> [(String, Bool)] -> Bool
simulate (IN a) c = findIn c a
simulate (NOT a) c = not $ simulate a c
simulate (AND a b) c = simulate a c && simulate b c
simulate (OR a b) c = simulate a c || simulate b c
simulate (XOR a b) c = simulate a c `xor` simulate b c

但是我们可以通过抽象运算符来简化它:

data Op1 = Not

data Op2 = And | Or | Xor

data Circ
  = IN String
  | Op1 Op1 Circ
  | Op2 Op2 Circ Circ

并与:

合作
func1 :: Op1 -> Bool -> Bool
func1 Not = not

func2 :: Op2 -> Bool -> Bool -> Bool
func2 And = (&&)
func2 Or = (&&)
func2 Xor = xor

simulate :: Circ -> [(String, Bool)] -> Bool
simulate (IN a) c = findIn c a
simulate (Op1 f a) c = func1 f (simulate a c)
simulate (Op2 f a b) c = func2 f (simulate a c) (simulate b c)
© www.soinside.com 2019 - 2024. All rights reserved.