gpt4 book ai didi

haskell - 函数的模式匹配

转载 作者:行者123 更新时间:2023-12-02 14:06:57 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com