“模式匹配"指的是“模式匹配".Haskell中的类型 [英] "Pattern-matching" types in Haskell
问题描述
我想要一个函数 f
,该函数在 Int
上充当增量,并在所有其他类型上充当身份.我试图启用 TypeApplications
扩展名,并以最简单的方式做到这一点:
I want a function f
that acts as an increment on Int
s and as an identity on all the other types. I tried to enable the TypeApplications
extension and do this the most straight-forward way possible:
f :: forall a. a -> a
f @Int x = x + 1
f @_ x = x
但是该扩展程序不启用此类模式:
But the extension does not enable such patterns:
<interactive>:6:1: error: Parse error in pattern: f @Int
Haskell中是否存在类型(或类似机制)的模式匹配?
Is there pattern-matching for types (or a similar mechanism) in Haskell?
推荐答案
如上所述,这在Haskell中是不可能实现的,因为它会违反称为"parametricity"的参数多态性的基本属性之一,从而确保了任何多态函数满足称为自由定理"的特定属性.
As stated, this is impossible to achieve in Haskell since it would violate one of the fundamental properties of parametric polymorphism known as "parametricity", which ensures that any polymorphic function satisfies a specific property knows as the "free theorem".
特别是类型为 forall a的终止函数.a->
必须是身份.没有其他可能的实现方式.
In particular, a terminating function of type forall a. a -> a
must be the identity. There are no other possible implementations.
话虽这么说,如果我们允许对 a
类型的约束,则这成为可能.通常,运行时类型测试是通过 Typeable
类型类在Haskell中完成的:
That being said, if we allow a constraint on type a
, this becomes possible. Typically, run-time type-testing is done in Haskell through the Typeable
type class:
f :: forall a. Typeable a => a -> a
f x = case eqT @a @Int of -- Is a ~ Int ?
Just Refl -> x + 1 -- If it is, we can add one.
Nothing -> x -- Otherwise, return x as-is.
这需要大量GHC扩展,并导入 Data.Typeable
.
This requires a bunch of GHC extensions, and to import Data.Typeable
.
这篇关于“模式匹配"指的是“模式匹配".Haskell中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!