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

Haskell-确定if-then-else表达式中使用了什么数据类型构造函数,haskell,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

我有以下代码:

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语句,因为我的实际代码要长得多,复杂得多。不,没有(除了将您的值与完全构造的实例进行比较……只有当您的值实际上是
Eq
可以的时候,它才起作用)

您可以自己编写该函数,或者使用case语句:

case aValue of
   Constructor x -> something
   Konstruktor y -> somethingElse
无关注:

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

这表明您的代码可能太复杂,您可能应该将其分解为更小的函数。在一个函数中执行太多操作会使编写它变得困难,以后几乎不可能读取它。

不,没有(除了将您的值与完全构造的实例进行比较……只有在您的值实际上是
Eq
可执行的情况下才有效)

您可以自己编写该函数,或者使用case语句:

case aValue of
   Constructor x -> something
   Konstruktor y -> somethingElse
无关注:

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


这表明您的代码可能太复杂,您可能应该将其分解为更小的函数。在一个函数中执行太多操作会使编写变得困难,而在以后几乎不可能读取它。

对于您的特定情况,这很容易:

data Instruction = IntDec String String | Stop
                 deriving Eq

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

对于您的特殊情况,这很容易:

data Instruction = IntDec String String | Stop
                 deriving Eq

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

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

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

isNothing :: Maybe a -> Bool
isNothing Nothing = True
isNothing _       = False
然后在if语句中使用
isJust
isNothing


请注意,
isJust
定义中的语法-
Just{}
(Just{}
相同,
{}
语法在构造函数有许多参数而您不关心其中任何参数时非常有用。

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

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

isNothing :: Maybe a -> Bool
isNothing Nothing = True
isNothing _       = False
然后在if语句中使用
isJust
isNothing


注意,
isJust
definition-
Just{}
中的语法与
(Just}
相同,
{}
语法在构造函数有许多参数而您不关心其中任何参数时非常有用。

模式匹配简化了事情。防护装置干净整洁。尽量避免使用大量相互交织的if语句,因为if语句最好用于小的子表达式。模式匹配可以简化事情。防护装置干净整洁。尽量避免使用大量相互交织的if语句,因为if语句最好用于小的子表达式。