我有一个函数,dir_con :: (Int -> Dir)
我想通过模式匹配来查找 dir_con 是哪个特定的构造函数。数据类型为:
data Dir = Define Int
| Equals Int
| Data Int
| LCset Int
| NoArg Int
因此,dir_con 将是 Define、Equals 等。它被传递给函数,我想像这样进行模式匹配:
case dir_con of
NoArg -> Do something specific
_ -> Do something for the rest
编译器不喜欢这样。错误消息是Couldn't match expected type 'Int -> Dir' with actual type 'Dir'
。
当然NoArg
是 (Int -> Dir)
类型的构造函数? Haskell 不允许这种类型的模式匹配吗?我必须这样做,因为 Dir
构造函数来自 map 。有没有关于我如何治疗的建议NoArg
不同吗?
最佳答案
两种方式:
case dir_con of
NoArg _ -> Do something specific
_ -> Do something for the rest
您匹配的是/value/而不是构造函数。
或者,使用记录语法:
case dir_con of
NoArg {} -> Do something specific
_ -> Do something for the rest
这是良好的卫生习惯,因为它在字段数量方面是中性的。
关于haskell - 函数的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15439945/