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