1

私はHaskellを習っており、このプログラムを実装しようとしています。私はカスタムデータ型を持っていますカスタムデータ型とパラメータの比較

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

この場合、このタイプの値を返すメソッドgetInputがあります。

今、このタイプの値をディスパッチする方法が混乱しています。私は、入力が私もcaseを使用しようとしたNumber x

であるかどうかを知りたいの方法

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 

あります

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ブランチ内にパラメータを持つ型または複数の文を持つことはできますか?

+0

@MathematicalOrchid。それはうまくいかなかった。私は試した。また、ans = op ans nとすると、それはinifniteループになることに気づくでしょう。 –

+1

@WaqarAhmedm 'let ans = op ans n' - これは再帰的に*それ自身で' ans'を定義します。あなたは新しい名前を使う必要があります。この場合、たいていは素数 '' 'を使用します:' 'ans '= op ans n' – luqui

+0

@ luqui..i got..thanks。もう1つの質問ですが、なぜsimpleCalculatorメソッドから値を返さないのは良いと思いますか? –

答えて

1

Eqインスタンスの場合は、derivationを使用してコンパイラに作業を依頼することができます。つまり、

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

こんにちはサボテン、私はこの同じ論理を昨日試して、それは働いた。私はans = ans op xを使用すると混乱します。それは無限ループに向かいます。なぜ起こっているのか教えてください。 –

+0

これは 'let ans = ans op x'を実行すると、右側の' ans'は同じ 'ans'が定義されていることを意味します。 – Cactus

+0

ありがとう、もう...もう1つ質問ですが、この場合はsimpleCalculatorメソッドのようなメソッドから値を返さないのはなぜ良いと思いますか? –

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を導き出すことはできません。

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 

をあなたの非稼働コードで正しい軌道に乗ってほとんどだ

+0

私はすでにこのようにしています。スイッチの場合に複数のステートメントを実行するには? –

+0

私のコードを参照してください。ハスケルでは、ステートメントを実行しません。それらは実行されていないと述べられています。 – bipll

関連する問題