【发布时间】:2016-05-08 12:10:38
【问题描述】:
我正在学习 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 分支中有多个语句?
【问题讨论】:
-
@MathematicalOrchid。它没有用。我试过。我还注意到它在 let ans = op ans n 上进入 inifnite 循环
-
@WaqarAhmedm
let ans = op ans n-- 这递归地根据自身定义ans。您需要使用新名称,在这种情况下我们经常使用素数':let ans' = op ans n -
@luqui..我明白了..谢谢。还有一个问题,为什么不从 simpleCalculator 方法返回值是好的?
标签: haskell pattern-matching algebraic-data-types do-notation