具有任一输入的Haskell函数

时间:2019-01-10 07:06:41

标签: haskell either

我似乎无法编写一个简单的haskell函数来获取Either输入并使用它。这是我写的:

$ cat main.hs
module Main( main ) where

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

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

这显然可以正常工作:

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

但是当我删除评论并使用第一个签名时,出现以下错误:

[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))

1 个答案:

答案 0 :(得分:10)

如果您定义一个接受Either String Int的函数,则不能仅将Int传递给它。在您的情况下,您可能希望传递Right 8Left "8"

module Main( main ) where

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

main :: IO ()
main = do
  print(myAtoi(Right 8))
  print(myAtoi(Left "8"))