【问题标题】:How do I use putStrLn on Maybe value in Haskell Stack test?如何在 Haskell Stack 测试中对 Maybe 值使用 putStrLn?
【发布时间】: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 of printMaybe' 防止约束(Show a0)' from being solved. Probable fix: use a type annotation to specify what a0' 应该是。 这些潜在的实例存在: instance Show Ordering -- 定义在GHC.Show' instance Show Integer -- Defined in GHC.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 类型是什么。

标签: haskell maybe


【解决方案1】:

正如错误所说,问题不在于您的printMaybe,而在于您的do 块中的printMaybe Nothing,从那时起就不清楚a 类型是什么。

因此,您可能有类似:K

main = do
    putStrLn "====== Tests Start ======"
    putStrLn (printMaybe Nothing)

但不清楚Maybe a 类型的a 是什么Nothing。你可以给编译器一个提示:

main = do
    putStrLn "====== Tests Start ======"
    putStrLn (printMaybe (Nothing :: Maybe Int))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多