函数的模式匹配

Dar*_*zak 2 haskell functional-programming pattern-matching

我有一个功能, dir_con :: (Int -> Dir)

我想模式匹配找到哪个特定的构造函数dir_con.数据类型是:

data Dir = Define Int
         | Equals Int 
         | Data Int  
         | LCset Int
         | NoArg Int
Run Code Online (Sandbox Code Playgroud)

所以,dir_con将是Define,Equals等.它被传递给一个函数,我想像这样模式匹配:

case dir_con of
    NoArg -> Do something specific
    _     -> Do something for the rest
Run Code Online (Sandbox Code Playgroud)

编译器不喜欢这样.错误信息是Couldn't match expected type 'Int -> Dir' with actual type 'Dir'.

肯定NoArg是类型的构造函数(Int -> Dir)?Haskell不允许这种类型的模式匹配吗?我必须这样做,因为Dir构造函数来自地图.有关于我如何NoArg区别对待的建议吗?

Don*_*art 5

两种方式:

case dir_con of
    NoArg _ -> Do something specific
    _     -> Do something for the rest
Run Code Online (Sandbox Code Playgroud)

您正在匹配/ value /而不是构造函数.

或者,使用者记录语法:

case dir_con of
    NoArg {} -> Do something specific
    _     -> Do something for the rest
Run Code Online (Sandbox Code Playgroud)

这是良好的卫生,因为它在田地数量方面是中性的.