haskell - 具有任意输入的 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))
解决方案
如果你定义了一个函数,Either String Int
那么你不能只传递一个Int
给它。在您的情况下,您可能想通过Right 8
或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"))
推荐阅读
- google-apps-script - Google 表格:如何根据文本和日期在表格之间移动数据
- css - Less中的&符号和双&符号有什么区别?
- java - HashMap 到 Spring JPA 的映射扩展
- swift - 如何计算两点之间关于 3-D 空间中相机方向的角度
- r - 将两个包含布尔值的数据帧与“或”逻辑结合起来
- teamcity - 彻底卸载 TeamCity
- angular - cdkDropList 不保存项目的新顺序
- unity3d - 将左手 Y-up(例如 Unity)坐标和旋转转换为右手 Z-up (3DS Max)
- java - 如何验证是否在接口的 impl 上调用了方法
- javascript - NodeJS (JavaScript/TypeScript) - 读取 Parquet 文件时出错