haskell - 如何在幻像类型的模式匹配中指定类型参数

标签 haskell pattern-matching type-parameter

假设我有这个:

data PT1
data PT2
data DT1 a = DT1 { field :: Int }

newtype DT2 a = DT2 (DT1 a)

f :: Int -> DT2 a -> Int
f x (DT2 (DT1 PT1 field)) = 5 -- How do I specify the type param?
f x (DT2 (DT1 PT2 field)) = 7 -- How do I specify the type param?

问题在评论里。上面的内容无法编译。我想根据类型参数进行不同的模式匹配。我该怎么做?

最佳答案

您无法对类型进行模式匹配。你可以做的是使用这样的类型类:

class Effable t where
  f :: Int -> t -> Int

instance Effable (DT2 PT1) where
  f x (DT2 _) = 5

instance Effable (DT2 PT2) where
  f x (DT2 _) = 7

关于haskell - 如何在幻像类型的模式匹配中指定类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4909427/

相关文章:

c# - 在运行时传递 Type 参数

haskell - 为什么有一个单独的类型模块?

haskell - 对不同大小的输入运行 Haskell 基准测试

Linux 一元运算符检查具有模式名称的文件是否存在

haskell - 模式匹配数据类型及其在 Haskell 中的嵌套名称

string - 如何在不使用 OverloadedStrings 的情况下对文本进行模式匹配?

haskell - 全局变量 “total” 未正确更新

haskell - Haskell 中的 Goto : Can anyone explain this seemingly insane effect of continuation monad usage?

scala - 如何为所有数字类型创建通用类?

Java:使用具有通配符类型参数的类函数