【发布时间】:2021-02-20 01:22:09
【问题描述】:
我正在使用 Haskell Stack 创建一个程序。我的程序运行良好,但我想编写一个测试文件,以便可以在现有程序上运行 stack test。我的问题是我的测试函数返回一个 Maybe 类型,无法使用语法putStrLn f 输出。我正在尝试在我的测试文件中编写一个函数,该函数接受一个 Maybe 值,如果给定 Nothing,则返回“Nothing”,如果给定 Just a,则返回包含 a 的字符串。
到目前为止,这是我的代码:
printMaybe :: Show a => Maybe a -> String
printMaybe Nothing = "Nothing"
printMaybe (Just a) = show a
并且 main 包含该行
putStrLn $ printMaybe (Nothing)
我的错误信息是:
test\Spec.hs:12:16: 错误: * 模糊类型变量
a0' arising from a use ofprintMaybe' 防止约束(Show a0)' from being solved. Probable fix: use a type annotation to specify whata0' 应该是。 这些潜在的实例存在: instance Show Ordering -- 定义在GHC.Show' instance Show Integer -- Defined inGHC.Show' instance Show a => Show (Maybe a) -- 定义在GHC.Show' ...plus 22 others ...plus 27 instances involving out-of-scope types (use -fprint-potential-instances to see them all) * In the second argument of($)',即`printMaybe (Nothing)' 在“do”块的 stmt 中:putStrLn $ printMaybe (Nothing) 在表达式中: 做 putStrLn ("====== 测试开始 ======") putStrLn $ printMaybe(无) | 12 | putStrLn $ printMaybe(无) | ^^^^^^^^^^^^^^^^^^^^
任何帮助将不胜感激:)
【问题讨论】:
-
正如错误所说,问题不在于您的
printMaybe,而在于您的do块中的printMaybe Nothing,从那时起就不清楚a类型是什么。