假设我有以下代码(<>
中的文本是速记,实际上不是代码的一部分(:
data A = <something>
defaultA :: A
defaultA = <Really complicated expression of type A>
现在我想在defaultA
上有一个函数模式匹配,像这样:
f defaultA = <case 1>
f _ = <case 2>
但是,第一行中的defaultA
将成为新变量,而不是意味着参数等于 defaultA
的条件。我知道实现我想要的最好的方法是:
f x | x == defaultA = <case 1>
f _ = <case 2>
有谁知道更好的方法?
如果 defaultA
的定义仅包含构造函数调用,则可以使用模式同义词。
{-# LANGUAGE PatternSynonyms #-}
data A = A Int
pattern DefaultA = A 3
isDefaultA DefaultA = putStrLn "it was a default"
isDefaultA _ = putStrLn "it was not a default"
不过,这并不是一个特别习惯的PatternSynonyms
部署。我可能会坚持使用 Haskell 98,使用一个稍微稍微冗长的保护条款和平等测试。
data A = A Int deriving Eq
defaultA = A 3
isDefaultA a
| a == defaultA = putStrLn "it was a default"
| otherwise = putStrLn "it was not a default"
模式同义词确实有用的地方是,当您使用自由 monads 或点菜数据类型等模式进行数据类型泛型编程时,用于包装强加给您的嘈杂的库构造函数调用。
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TypeOperators #-}
-- fixed point of functor
newtype Expr f = In (f (Expr f))
-- functor coproduct
data (f :+: g) a = Inl (f a) | Inr (g a)
-- now plug in custom code
data Add r = Add_ r r
data Val r = Val_ Int
type HuttonsRazor = Expr (Add :+: Val)
pattern Add x y = In (Inl (Add_ x y))
pattern Val x = In (Inr (Val_ x))
eval :: HuttonsRazor -> Int
eval (Add x y) = eval x + eval y
eval (Val x) = x
ViewPattern扩展
{-# LANGUAGE ViewPatterns #-}
data A = A Int | B Char deriving (Eq, Show)
complexA = A 34
complexB = B 'z'
isComplexA = (complexA ==)
isComplexB = (complexB ==)
complexF (isComplexA -> True) = print "complexA"
complexF (isComplexB -> True) = print "complexB"
complexF _ = print "too complex"
main = do
complexF complexA
complexF complexB
complexF $ A 55