[英]Is pattern matching in Set Comprehensions in Haskell possible, or what is an alternative?
[英]Cleaner Alternative to Extensive Pattern Matching in Haskell
现在,我有一些基本上像这样的代码:
data Expression
= Literal Bool
| Variable String
| Not Expression
| Or Expression Expression
| And Expression Expression
deriving Eq
simplify :: Expression -> Expression
simplify (Literal b) = Literal b
simplify (Variable s) = Variable s
simplify (Not e) = case simplify e of
(Literal b) -> Literal (not b)
e' -> Not e'
simplify (And a b) = case (simplify a, simplify b) of
(Literal False, _) -> Literal False
(_, Literal False) -> Literal False
(a', b') -> And a' b'
simplify (Or a b) = case (simplify a, simplify b) of
(Literal True, _) -> Literal True
(_, Literal True) -> Literal True
(a', b') -> Or a' b'
还有更多关于可以简化布尔表达式的所有方式的模式。 然而,随着我添加更多运营商和规则,这种情况越来越大,感觉很笨拙。 特别是因为一些规则需要加两次来解释交换性。
我怎样才能很好地重构许多模式,其中一些(大多数,我会说)甚至是对称的(例如,采用And和Or模式)?
现在,添加一个规则来简化And (Variable "x") (Not (Variable "x"))
到Literal False
需要我添加两个嵌套规则,这几乎是最优的。
基本上问题是你必须一遍又一遍地写出每个子句中子表达式的simplify
。 在考虑涉及顶级运营商的法律之前,首先完成所有子表达式会更好。 一种简单的方法是添加一个simplify
的辅助版本,它不会递归:
simplify :: Expression -> Expression
simplify (Literal b) = Literal b
simplify (Variable s) = Variable s
simplify (Not e) = simplify' . Not $ simplify e
simplify (And a b) = simplify' $ And (simplify a) (simplify b)
simplify (Or a b) = simplify' $ Or (simplify a) (simplify b)
simplify' :: Expression -> Expression
simplify' (Not (Literal b)) = Literal $ not b
simplify' (And (Literal False) _) = Literal False
...
由于您在布尔运算中只进行了少量操作,这可能是最明智的方法。 但是,通过更多操作, simplify
的重复可能仍然值得避免。 为此,您可以将一元和二元操作混合到一个公共构造函数:
data Expression
= Literal Bool
| Variable String
| BoolPrefix BoolPrefix Expression
| BoolInfix BoolInfix Expression Expression
deriving Eq
data BoolPrefix = Negation
data BoolInfix = AndOp | OrOp
然后你就是
simplify (Literal b) = Literal b
simplify (Variable s) = Variable s
simplify (BoolPrefix bpf e) = simplify' . BoolPrefix bpf $ simplify e
simplify (BoolInfix bifx a b) = simplify' $ BoolInfix bifx (simplify a) (simplify b)
显然这会使simplify'
更加尴尬,所以也许不是一个好主意。 但是,您可以通过定义专门的模式同义词来解决这种语法开销:
{-# LANGUAGE PatternSynonyms #-}
pattern Not :: Expression -> Expression
pattern Not x = BoolPrefix Negation x
infixr 3 :∧
pattern (:∧) :: Expression -> Expression -> Expression
pattern a:∧b = BoolInfix AndOp a b
infixr 2 :∨
pattern (:∨) :: Expression -> Expression -> Expression
pattern a:∨b = BoolInfix OrOp a b
就此而言,也许也是如此
pattern F, T :: Expression
pattern F = Literal False
pattern T = Literal True
有了它,你就可以写了
simplify' :: Expression -> Expression
simplify' (Not (Literal b)) = Literal $ not b
simplify' (F :∧ _) = F
simplify' (_ :∧ F) = F
simplify' (T :∨ _) = T
simplify' (a :∧ Not b) | a==b = T
...
我应该添加一个警告: 当我尝试类似于那些模式同义词的东西,而不是布尔值但是仿射映射时,它使编译器非常慢 。 (此外,GHC-7.10尚未支持多态模式同义词;截至目前,这已经发生了很大变化。)
还要注意,所有这些通常不会产生最简单的形式 - 为此,您需要找到simplify
的固定点。
你可以做的一件事是在你构造时简化,而不是先构建然后重复破坏。 所以:
module Simple (Expression, true, false, var, not, or, and) where
import Prelude hiding (not, or, and)
data Expression
= Literal Bool
| Variable String
| Not Expression
| Or Expression Expression
| And Expression Expression
deriving (Eq, Ord, Read, Show)
true = Literal True
false = Literal False
var = Variable
not (Literal True) = false
not (Literal False) = true
not x = Not x
or (Literal True) _ = true
or _ (Literal True) = true
or x y = Or x y
and (Literal False) _ = false
and _ (Literal False) = false
and x y = And x y
我们可以在ghci中尝试一下:
> and (var "x") (and (var "y") false)
Literal False
请注意,构造函数不会导出:这可以确保构造其中一个的人无法避免简化过程。 实际上,这可能是一个缺点; 偶尔看到“完整”形式很高兴。 处理此问题的标准方法是使导出的智能构造函数成为类类的一部分; 您可以使用它们来构建“完整”表单或“简化”表单。 为了避免必须两次定义类型,我们可以使用newtype或phantom参数; 我会选择后者来减少模式匹配中的噪音。
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
module Simple (Format(..), true, false, var, not, or, and) where
import Prelude hiding (not, or, and)
data Format = Explicit | Simplified
data Expression (a :: Format)
= Literal Bool
| Variable String
| Not (Expression a)
| Or (Expression a) (Expression a)
| And (Expression a) (Expression a)
deriving (Eq, Ord, Read, Show)
class Expr e where
true, false :: e
var :: String -> e
not :: e -> e
or, and :: e -> e -> e
instance Expr (Expression Explicit) where
true = Literal True
false = Literal False
var = Variable
not = Not
or = Or
and = And
instance Expr (Expression Simplified) where
true = Literal True
false = Literal False
var = Variable
not (Literal True) = false
not (Literal False) = true
not x = Not x
or (Literal True) _ = true
or _ (Literal True) = true
or x y = Or x y
and (Literal False) _ = false
and _ (Literal False) = false
and x y = And x y
现在在ghci中,我们可以通过两种不同的方式“运行”相同的术语:
> :set -XDataKinds
> and (var "x") (and (var "y") false) :: Expression Explicit
And (Variable "x") (And (Variable "y") (Literal False))
> and (var "x") (and (var "y") false) :: Expression Simplified
Literal False
您可能希望稍后添加更多规则; 例如,也许你想要:
and (Variable x) (Not (Variable y)) | x == y = false
and (Not (Variable x)) (Variable y) | x == y = false
不得不重复两种模式的“顺序”有点烦人。 我们应该抽象一下! 数据声明和类将是相同的,但我们会添加辅助功能eitherOrder
中的定义,并用它and
和or
。 这是使用这个想法(以及我们最终版本的模块)的更完整的简化集:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
module Simple (Format(..), true, false, var, not, or, and) where
import Data.Maybe
import Data.Monoid
import Prelude hiding (not, or, and)
import Control.Applicative ((<|>))
data Format = Explicit | Simplified
data Expression (a :: Format)
= Literal Bool
| Variable String
| Not (Expression a)
| Or (Expression a) (Expression a)
| And (Expression a) (Expression a)
deriving (Eq, Ord, Read, Show)
class Expr e where
true, false :: e
var :: String -> e
not :: e -> e
or, and :: e -> e -> e
instance Expr (Expression Explicit) where
true = Literal True
false = Literal False
var = Variable
not = Not
or = Or
and = And
eitherOrder :: (e -> e -> e)
-> (e -> e -> Maybe e)
-> e -> e -> e
eitherOrder fExplicit fSimplified x y = fromMaybe
(fExplicit x y)
(fSimplified x y <|> fSimplified y x)
instance Expr (Expression Simplified) where
true = Literal True
false = Literal False
var = Variable
not (Literal True) = false
not (Literal False) = true
not (Not x) = x
not x = Not x
or = eitherOrder Or go where
go (Literal True) _ = Just true
go (Literal False) x = Just x
go (Variable x) (Variable y) | x == y = Just (var x)
go (Variable x) (Not (Variable y)) | x == y = Just true
go _ _ = Nothing
and = eitherOrder And go where
go (Literal True) x = Just x
go (Literal False) _ = Just false
go (Variable x) (Variable y) | x == y = Just (var x)
go (Variable x) (Not (Variable y)) | x == y = Just false
go _ _ = Nothing
现在在ghci中我们可以做更复杂的简化,例如:
> and (not (not (var "x"))) (var "x") :: Expression Simplified
Variable "x"
即使我们只写了一个重写规则的顺序,两个命令都正常工作:
> and (not (var "x")) (var "x") :: Expression Simplified
Literal False
> and (var "x") (not (var "x")) :: Expression Simplified
Literal False
我认为爱因斯坦说:“尽可能地简化,但不能再简化。” 你有一个复杂的数据类型和相应复杂的概念,所以我认为任何技术只能对手头的问题更加清晰。
也就是说,第一种选择是使用案例结构。
simplify x = case x of
Literal _ -> x
Variable _ -> x
Not e -> simplifyNot $ simplify e
...
where
sharedFunc1 = ...
sharedFunc2 = ...
这具有包括共享功能的额外好处,所述共享功能可用于所有情况但不能用于顶级命名空间。 我也喜欢这些案例如何从括号中解脱出来。 (另请注意,在前两种情况下,我只返回原始术语,而不是创建新术语)。 我经常使用这种结构来打破其他简化函数,就像Not
的情况一样。
特别是这个问题可能有助于将Expression
放在底层fmap
函数上,这样您就可以简化子表达式,然后执行给定大小写的特定组合。 它看起来如下所示:
simplify :: Expression' -> Expression'
simplify = Exp . reduce . fmap simplify . unExp
这里的步骤是将Expression'
展开到底层的functor表示中,映射底层术语的简化,然后减少这种简化并重新包装到新的Expression'
{-# Language DeriveFunctor #-}
newtype Expression' = Exp { unExp :: ExpressionF Expression' }
data ExpressionF e
= Literal Bool
| Variable String
| Not e
| Or e e
| And e e
deriving (Eq,Functor)
现在,我已经将复杂性推到了reduce
函数中,它只是稍微复杂一点,因为它不必担心首先减少子项。 但它现在只包含将一个术语与另一个术语合并的业务逻辑。
这可能是也可能不是一种很好的技术,但它可以使一些增强更容易。 例如,如果可以用您的语言形成无效表达式,则可以使用Maybe
值失败来简化该表达式。
simplifyMb :: Expression' -> Maybe Expression'
simplifyMb = fmap Exp . reduceMb <=< traverse simplifyMb . unExp
这里, traverse
将simplfyMb
应用于ExpressionF
,导致Maybe
子类的表达式, ExpressionF (Maybe Expression')
,然后如果任何子类是Nothing
,它将返回Nothing
,如果所有都是Just x
,它将返回Just (e::ExpressionF Expression')
。 Traverse实际上并没有像这样分成不同的阶段,但它更容易解释,就好像它一样。 另请注意,您需要DeriveTraversable和DeriveFoldable的语言编译指示,以及ExpressionF
数据类型的派生语句。
不足之处? 好吧,对于其中一个,你的代码的污垢将随处可见一堆Exp
包装器。 考虑以下简单术语的simplfyMb
的应用:
simplifyMb (Exp $ Not (Exp $ Literal True))
如果您了解上面的traverse
和fmap
模式,您可以在很多地方重复使用它,这样做很好。 我也相信以这种方式定义简化使得它对于特定的ExpressionF
结构可能变得更加健壮。 它没有提到它们,所以深度简化不会受到重构的影响。 另一方面,reduce函数将是。
继续使用Binary Op Expression Expression
想法,我们可以得到以下数据类型:
data Expression
= Literal Bool
| Variable String
| Not Expression
| Binary Op Expression Expression
deriving Eq
data Op = Or | And deriving Eq
并辅助功能
{-# LANGUAGE ViewPatterns #-}
simplifyBinary :: Op -> Expression -> Expression -> Expression
simplifyBinary binop (simplify -> leftexp) (simplify -> rightexp) =
case oneway binop leftexp rightexp ++ oneway binop rightexp leftexp of
simplified : _ -> simplified
[] -> Binary binop leftexp rightexp
where
oneway :: Op -> Expression -> Expression -> [Expression]
oneway And (Literal False) _ = [Literal False]
oneway Or (Literal True) _ = [Literal True]
-- more cases here
oneway _ _ _ = []
这个想法是,你干脆把简化案件oneway
然后simplifyBinary
将采取扭转参数的照顾,以避免写对称的情况。
您可以为所有二进制操作编写通用的简化器:
simplifyBinWith :: (Bool -> Bool -> Bool) -- the boolean operation
-> (Expression -> Expression -> Expression) -- the constructor
-> Expression -> Expression -- the two operands
-> Expression) -- the simplified result
simplifyBinWith op cons a b = case (simplify a, simplify b) of
(Literal x, Literal y) -> Literal (op x y)
(Literal x, b') -> tryAll (x `op`) b'
(a', Literal y) -> tryAll (`op` y) a'
(a', b') -> cons a' b'
where
tryAll f term = case (f True, f False) of -- what would f do if term was true of false
(True, True) -> Literal True
(True, False) -> term
(False, True) -> Not term
(False, False) -> Literal False
这样,你的simplify
功能就会变成
simplify :: Expression -> Expression
simplify (Not e) = case simplify e of
(Literal b) -> Literal (not b)
e' -> Not e'
simplify (And a b) = simplifyBinWith (&&) And a b
simplify (Or a b) = simplifyBinWith (||) Or a b
simplify t = t
并且可以很容易地扩展到更多的二进制操作。 它也将与正常工作Binary Op Expression Expression
的想法,你会经过Op
,而不是Expression
构造函数simplifyBinWith
和模式simplify
可以推广:
simplify :: Expression -> Expression
simplify (Not e) = case simplify e of
(Literal b) -> Literal (not b)
e' -> Not e'
simplify (Binary op a b) = simplifyBinWith (case op of
And -> (&&)
Or -> (||)
Xor -> (/=)
Implies -> (<=)
Equals -> (==)
…
) op a b
simplify t = t
where
simplifyBinWith f op a b = case (simplify a, simplify b) of
(Literal x, Literal y) -> Literal (f x y)
…
(a', b') -> Binary op a' b'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.