aaliyah
aaliyah

Reputation: 17

Haskell use input as operator

how do i use the input as an operator? this is my code:

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 gives me this error:

   * 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

i dont really know what ghci is trying to tell me with that.

i've also tried to write line 9 like this:

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

is it wrong to try to convert op to the Num type? is op a string when i use <- getLine?

thank you

Upvotes: 1

Views: 196

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

Num is a typeclass, not a type, hence read op :: Num makes not much sense.

Furthermore, parsing to a function is not possible, so if you use read op :: Int -> Int, that will not work either.

You can work with a lookup table for example where you map "+" to (+), etc.:

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

then for the reader we use:

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

Upvotes: 4

Related Questions