Haskell - 在模式匹配中使用常量

时间:2016-02-16 09:54:02

标签: haskell syntax pattern-matching pattern-synonyms

我们说我有以下代码(<>中的文字是速记,实际上不是代码的一部分):

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>

有没有人知道更好的方法?

2 个答案:

答案 0 :(得分:6)

如果defaultA的定义仅包含构造函数调用,则可以使用pattern synonym

{-# 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"

模式同义词的用处在于,当您使用 free monads这样的模式进行数据类型泛型编程时,会包含强加给您的嘈杂库构造函数调用Data Types a la Carte

{-# 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

答案 1 :(得分:2)

您可以使用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