Haskell 编写模式同义词以隐藏构造函数
考虑以下几点:Haskell 编写模式同义词以隐藏构造函数,haskell,pattern-synonyms,Haskell,Pattern Synonyms,考虑以下几点: module MyModule ( A(FortyTwo), -- Note we don't expose PrivateA B(P) -- Nor PrivateB ) where pattern FortyTwo = A 42 newtype A = PrivateA Int data B = PrivateB Int Int pattern P :: Int -> A -> B 我怎么写模式p 基本上我想说: f :: B -> Stri
module MyModule (
A(FortyTwo), -- Note we don't expose PrivateA
B(P) -- Nor PrivateB
) where
pattern FortyTwo = A 42
newtype A = PrivateA Int
data B = PrivateB Int Int
pattern P :: Int -> A -> B
我怎么写模式p
基本上我想说:
f :: B -> String
f (P 2 FortyTwo) = "The meaning of life"
也就是说,能够在不直接引用私有构造函数PrivateA和PrivateB的情况下进行模式匹配。首先,请记住newtype只能用于具有单个参数的数据构造函数,因此a可以是newtype,而B不能
现在,您用于FortyTwo的模式语法被称为隐式双向。就是
pattern FortyTwo :: A
pattern FortyTwo = PrivateA 42
我们使用=并真正意味着平等。它说我可以用FortyTwo构造一个A,如果我有一个A,我可以用FortyTwo在上面进行模式匹配。这是最简单的形式,在参数很好地定向的简单情况下非常有用
但现实世界并不是那么简单。因此,GHC为我们提供了一种称为显式双向模式的方法。简而言之,我们可以显式地指定我们希望表达式在模式上下文中的行为以及希望它在表达式上下文中的行为。编译器没有也不能检查这两个表达式作为一对是否具有内聚意义,所以我们可以用它来做一些类似这样的废话
pattern Nonsense :: Int -> Int
pattern Nonsense n <- n where
Nonsense _ = 42
它实际上只是将函数调用移到等号的另一边,在某些情况下,这对于编写简洁的代码来说非常方便。它在定义模式同义词时也很有用
pattern P :: Int -> A -> B
pattern P n a <- PrivateB n (PrivateA -> a) where
P n (PrivateA a) = PrivateB n a
首先,请记住,newtype只能与具有单个参数的数据构造函数一起使用,因此a可以是newtype,但B不能
现在,您用于FortyTwo的模式语法被称为隐式双向。就是
pattern FortyTwo :: A
pattern FortyTwo = PrivateA 42
我们使用=并真正意味着平等。它说我可以用FortyTwo构造一个A,如果我有一个A,我可以用FortyTwo在上面进行模式匹配。这是最简单的形式,在参数很好地定向的简单情况下非常有用
但现实世界并不是那么简单。因此,GHC为我们提供了一种称为显式双向模式的方法。简而言之,我们可以显式地指定我们希望表达式在模式上下文中的行为以及希望它在表达式上下文中的行为。编译器没有也不能检查这两个表达式作为一对是否具有内聚意义,所以我们可以用它来做一些类似这样的废话
pattern Nonsense :: Int -> Int
pattern Nonsense n <- n where
Nonsense _ = 42
它实际上只是将函数调用移到等号的另一边,在某些情况下,这对于编写简洁的代码来说非常方便。它在定义模式同义词时也很有用
pattern P :: Int -> A -> B
pattern P n a <- PrivateB n (PrivateA -> a) where
P n (PrivateA a) = PrivateB n a