haskell - 函数的模式匹配

标签 haskell functional-programming pattern-matching

我有一个函数,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/

相关文章:

字符串上的 Haskell 模式匹配 - 为什么这不起作用?

Scala 多级模式匹配

haskell - 单击 "Enter"按键上的按钮

haskell - 为什么 DuplicateRecordFields 不能进行类型推断?

function - Haskell 以编程方式/动态定义函数

functional-programming - Scala 被称为 “functional language” 并不是因为它是图灵完备的

scala - 我如何解决这个 Scala 函数参数类型删除错误?

Haskell:为什么模式匹配适用于类型而不是相等的实例?

haskell - 如何混合应用仿函数和箭头

c# - 将 LINQ-to-SQL 谓词组合成单个谓词