自定义数据类型与参数的比较

Comparison of custom data type with parameters

我正在学习 Haskell 并尝试实施此程序。我有一个自定义数据类型

data CalculatorInput 
    = Exit 
    | Error String 
    | Operator (Int -> Int -> Int)
    | Number Int

然后我有一个方法 getInput 其中 returns 这种类型的值。

现在我很困惑如何分派这种类型的值。我有一个方法

simpleCalculator :: Int -> (Int -> Int -> Int) -> IO ()
simpleCalculator ans op =  do
    input <- getInput   -- here i got the type as result
    if input == Exit then return()
    else if input == Number x then ans = ans op x; print ans
    else simpleCalculator ans op

我想知道输入是否是Number x

我也尝试使用 case:

simpleCalculator :: Int -> (Int -> Int -> Int) -> IO ()
simpleCalculator ans op =  do
    input <- getInput   -- here i got the type as result
    --case input of
    --  Exit -> return ()
    --  Error x -> print x
    --  Number n -> ans = ans op x; print ans  -- getting error here, multiple statement not possible
    --  _ -> simpleCalculator ans op

我也尝试创建 Eq 的实例

instance Eq CalculatorInput where
    (==) Exit Exit = True
    (==) (Number x) (Number y) = x == y
    (==) _ _ = False 

如何比较自定义数据类型与参数或在 case 分支中有多个语句?

使用case.

simpleCalculator ans op =  do
    input <- getInput   -- here i got the type as result
    case input of
        Exit -> return ()
        Number x -> print $ans `op` x
        _ -> simpleCalculator ans op

您无法为 CalculatorInput 推导 Eq,因为函数不是 Eq.

的实例

您的非工作代码几乎走在正确的轨道上:

simpleCalculator :: Int -> (Int -> Int -> Int) -> IO ()
simpleCalculator ans op =  do
    input <- getInput   -- here i got the type as result
    case input of
      Exit -> return ()
      Error x -> print x
      Number n -> ans = ans op x; print ans
      _ -> simpleCalculator ans op

您可以嵌套 do 符号,这样您就可以编写出以下正确的程序:

simpleCalculator :: Int -> (Int -> Int -> Int) -> IO ()
simpleCalculator ans op =  do
    input <- getInput   -- here i got the type as result
    case input of
      Exit -> return ()
      Error x -> print x
      Number n -> do
        let theAns = ans op x
        print theAns
      _ -> simpleCalculator ans op

至于Eq实例,你可以使用derivation让编译器为你完成工作,即写作

data CalculatorInput 
    = Exit 
    | Error String 
    | Operator (Int -> Int -> Int)
    | Number Int
    deriving Eq