1

我正在学习 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分支中有多个语句?

4

2 回答 2

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
于 2016-05-09T02:54:44.150 回答
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

你不能推导EqforCalculatorInput因为函数不是 的实例Eq

于 2016-05-08T12:37:13.740 回答