0

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

2
  • 1
    Num is a typeclass, not a type, hence read op :: Num makes not much sense. Furthermore parsing to a function is not possible. You can work with a lookup table for example where you map "+" to (+), etc. Commented Jan 17, 2022 at 17:25
  • 1
    read returns something with a Read instance. Unless there is a Read instance of Num a => a -> a -> a, you can't use read like this. (Theoretically, you could write such an instance yourself, but as an orphaned instance--one not defined in either the module where the type class is defined or in the module where the type is defined--it's not considered a good idea.) Commented Jan 17, 2022 at 17:32

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

@aaliyah: you can also use print solution, print = putStrLn . show.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.