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

时间:2016-05-08 12:10:38

标签: haskell pattern-matching algebraic-data-types do-notation

我正在学习Haskell并试图实现这个程序。我有自定义数据类型

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

然后我有一个方法getInput,它返回这种类型的值。

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

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分支中包含多个语句?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

使用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

您无法为Eq派生CalculatorInput因为函数不是Eq的实例。