Haskell 使用输入作为运算符

Haskell use input as operator

如何将输入用作运算符? 这是我的代码:

applyOperator :: IO()
applyOperator = do
 putStrLn "Input first Integer: "
 num1 <- getLine
 putStrLn "Input operator: "
 op <- getLine
 putStrLn "Input second Integer: "
 num2 <- getLine
 let solution = (read op :: Num) num1 num2
 putStrLn solution

ghci 给我这个错误:

   * Expecting one more argument to `Num'
      Expected a type, but `Num' has kind `* -> Constraint'
    * In an expression type signature: Num
      In the expression: read op :: Num
      In the expression: (read op :: Num) num1 num2

我真的不知道 ghci 想告诉我什么。

我也试过这样写第 9 行:

let solution = num1 ´(read op :: Num)´ num2

尝试将op转换为Num类型是不是错了?当我使用 <- getLineop 是一个字符串吗?

谢谢

Num 是类型类,而不是类型,因此 read op :: Num 没有多大意义。

此外,无法解析为函数,因此如果您使用 read op :: Int -> Int,那也不起作用。

您可以使用查找 table,例如将 "+" 映射到 (+),等等:

parseFunc :: String -> Int -> Int -> Int
parseFunc "+" = (+)
parseFunc "-" = (-)
parseFunc "*" = (*)

然后对于 reader 我们使用:

applyOperator :: IO()
applyOperator = do
  putStrLn "Input first Integer: "
  num1 <- readLn
  putStrLn "Input operator: "
  op <- getLine
  putStrLn "Input second Integer: "
  num2 <- readLn
  let solution = <strong>parseFunc op</strong> num1 num2
  print solution