0

I can't seem to write a simple haskell function that gets an Either input and use it. Here is what I wrote:

$ cat main.hs
module Main( main ) where

-- myAtoi :: Either String Int -> Int
myAtoi :: Int -> Int
myAtoi _ = 700

main :: IO ()
main = do
print(myAtoi(8))

And this obviously works fine:

$ ghc main.hs -o main
$ ./main
700

But when I remove the comment and use the first signature I get the following error:

[1 of 1] Compiling Main             ( main.hs, main.o )

main.hs:9:14: error:
    • No instance for (Num (Either String Int))
        arising from the literal ‘8’
    • In the first argument of ‘myAtoi’, namely ‘(8)’
      In the first argument of ‘print’, namely ‘(myAtoi (8))’
      In a stmt of a 'do' block: print (myAtoi (8))
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87

1 Answers1

10

If you define a function that takes Either String Int then you cannot just pass an Int to it. In your case you probably want to pass Right 8 or Left "8":

module Main( main ) where

myAtoi :: Either String Int -> Int
myAtoi _ = 700

main :: IO ()
main = do
  print(myAtoi(Right 8))
  print(myAtoi(Left "8"))
Karol Samborski
  • 2,757
  • 1
  • 11
  • 18