Haskell - 确定if-then-else表达式中使用的数据类型构造函数

时间:2014-11-16 01:27:46

标签: haskell

我有以下代码:

data Instruction = IntDec String String | Stop

run :: Instruction -> Bool
run inst = 
    if (isStop inst) then True
    else False
    where
        isStop :: Instruction -> Bool
        isStop (Stop) = True
        isStop _ = False

我的问题是有没有办法在if语句中执行相同的代码。 e.g。

run inst = 
        if (isTypeOf inst == Stop) then True
        else False

我知道我可以通过使用它来简化我的代码:

run Stop = True
run _ = False

但我想使用if语句,因为我的实际代码更长更复杂

3 个答案:

答案 0 :(得分:4)

不,没有(没有将你的价值与完全构造的实例进行比较......只有当你的价值实际上是Eq时才有效。)

所能做的就是自己编写这个函数,或者使用case语句:

case aValue of
   Constructor x -> something
   Konstruktor y -> somethingElse

无关的说明:

  

我想使用if语句,因为我的实际代码更长更复杂

这表明您的代码可能复杂,您可能应该将其分解为更小的函数。在一个单一的功能中做太多的事情会让它写得很难,而且几乎不可能在以后读它。

答案 1 :(得分:1)

您的特定情况很容易:

data Instruction = IntDec String String | Stop
                 deriving Eq

run :: Instruction -> Bool
run inst = inst == Stop

答案 2 :(得分:1)

您可以创建自己的查询功能。例如,在Data.Maybe中定义了两个函数:

isJust :: Maybe a -> Bool
isJust Just{}  = True
isJust _        = False

isNothing :: Maybe a -> Bool
isNothing Nothing = True
isNothing _       = False

然后在if语句中使用isJustisNothing

请注意isJust定义中的语法 - Just{}(Just _)相同,当构造函数包含许多参数且您没有参数时,{}语法很有用关心他们中的任何一个。

相关问题