gpt4 book ai didi

Haskell 空主函数

转载 作者:行者123 更新时间:2023-12-01 21:59:54 26 4
gpt4 key购买 nike

我正在使用一个 junk.hs 文件来加载 ghci。我没有使用我的主要功能,只是调用文件中的其他功能来测试它们,例如:

-- junk.hs
main :: IO ()
main = putStrLn "hello"

otherFunction a b = a + b

当我加载时:

Prelude> :l junk.hs
Prelude> otherFunction 1 2 -- good

这很好,因为我没有调用 main,而且因为我必须定义一些 main 函数,所以它完成了工作。

但是,什么是正确的最小空主函数?

我试过了

main :: IO ()
main = Nothing

这失败了

*Main> :load junk.hs
[1 of 1] Compiling Main ( junk.hs, interpreted )

junk.hs:2:8: error:
• Couldn't match expected type ‘IO ()’ with actual type ‘Maybe a0’
• In the expression: Nothing
In an equation for ‘main’: main = Nothing
|
2 | main = Nothing
| ^^^^^^^
Failed, no modules loaded.

最佳答案

Nothing 对于某些 a 具有类型 Maybe a,但从来没有 IO ()。所以这不能是 main 的值。

标准的空操作 main 操作是

main :: IO ()
main = return ()

这可以很好地执行,只是做...好吧,什么都不做

或者,如果您希望主操作静默执行,您可以做到这一点

main :: IO ()
main = error "This program should not be run."

或类似的东西。

其中一个最短的选项是

main=main::IO()

这将永远循环或因无限递归错误而崩溃。不用说,除非您感觉真的很懒并且知道没有其他人需要处理该代码,否则不要这样做...

关于Haskell 空主函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53951940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com