如何模式匹配typeclass值? [英] How to pattern match against a typeclass value?
问题描述
假设我在Haskell中定义了一个类型类,
Suppose that I define a typeclass in Haskell,
class (Bool a) where
false :: a
true :: a
为了定义一个通用的不是操作对于任何
Bool
,都需要对其潜在值进行模式匹配:
In order to define a generic not
operation for any Bool
, one would need to pattern match against its potential values:
not :: Bool a => a → a
not true = false
not false = true
不过,编译。我怎样才能使它工作?
That doesn't compile, though. How can I get it to work?
推荐答案
您无法像这样匹配类型类型值。类型类抽象出实际的基础类型,而模式匹配会暴露它。
You can't match against a typeclass value like this. Typeclasses abstract over the actual underlying type while pattern matching would expose it.
然而,仍然可以通过 ViewPatterns
扩展名。这个想法是包含一个函数,它接受你的抽象值,并为你提供一个代表视图结构的具体类型的值:
However, you can still get the same behavior and some nice syntax with the ViewPatterns
extension. The idea is to include a function which takes your abstract value and gives you a value of a concrete type that represents a view into the structure:
class (Bool a) where
true :: a
false :: a
asBool :: a -> Bool
现在您可以使用 asBool
函数在模式匹配中作为视图模式:
Now you can use the asBool
function in a pattern match as a view pattern:
not :: Bool a => a -> a
not (asBool -> True) = false
not (asBool -> False) = true
然而,请注意,这可能会导致 asBool
被计算两次,如果它隐藏昂贵的计算可能会成为问题。
However, note that this could result in asBool
being computed twice which could be an issue if it hides an expensive computation.
这篇关于如何模式匹配typeclass值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!