好的,所以继续我之前的问题后,我最终得到了以下代码:
module Main where
import Data.List
chain n | n == 0 = error "What are you on about?"
| n == 1 = [1]
| rem n 2 == 0 = n : chain (n `div` 2)
| otherwise = n : chain (3 * n + 1)
chainLength n = (n,length (chain n))
array = map chainLength [1..999]
lengths = map chainLength [1..1000000]
compareSnd (_, y1) (_, y2) = compare y1 y2
longestChain = maximumBy compareSnd lengths
Run Code Online (Sandbox Code Playgroud)
从GHCi开始,这可以很好地作为一个模块加载,但是运行longestChain会导致堆栈溢出.解决这个问题不是完全重写就是增加堆栈大小.所以我编译:ghc --make chain.hs
我收到一个错误:
chain.hs:1:0: The function 'main' is not defined in the module 'main'
Run Code Online (Sandbox Code Playgroud)
我需要在哪里放置main函数才能使其正确编译.
然后编译后,如何让它运行输出或使用命令?我假设:
ghc chain.o +RTS -K128M
Run Code Online (Sandbox Code Playgroud)
编译完成后,我只需要运行具有大堆栈大小的longestChain.
要在Haskell中编译可执行文件,您需要定义一个名为的函数main.像这样的东西:
main = print longestChain
Run Code Online (Sandbox Code Playgroud)
主模块中的任何位置.
退房GHC文档上ghc --make.