首页 > 解决方案 > 具有任意输入的 Haskell 函数

问题描述

我似乎无法编写一个简单的 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))

标签: haskelleither

解决方案


如果你定义了一个函数,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"))

推荐阅读