运行编译后的Haskell程序;出现错误。

4

好的,继续我之前的问题,我最终得到了以下代码:

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

从 GHCi 中作为模块加载没有问题,但运行 longestChain 会导致堆栈溢出。解决这个问题的方法不是完全重写,而是增加堆栈大小。 因此,我使用以下命令进行编译: ghc --make chain.hs
然后我遇到了一个错误:
chain.hs:1:0: The function 'main' is not defined in the module 'main'

我需要将主函数放在哪里才能使其正确编译。
一旦编译完成,如何运行输出或使用命令?
我猜想是通过:

ghc chain.o +RTS -K128M

编译完成后,我只需要用较大的堆栈大小运行longestChain即可。
2个回答

8

要在Haskell中编译可执行文件,您需要定义一个名为main的函数。像这样:

main = print longestChain

在主模块的任何位置可用。

查看GHC文档中有关ghc --make的信息。


谢谢,你真是救星。多亏了你的帮助,我的 Haskell 技能有了很大提高。 - Jonno_FTW
3
顺便提一句,我注意到你仍然称那些 [] 为数组。在 GHC 中有数组,但它们与 列表 不同。使用正确的术语会有所帮助。如果你想了解差异,请访问以下链接:http://www.cs.auckland.ac.nz/references/haskell/haskell-intro-html/arrays.html 和 http://www.haskell.org/tutorial/goodies.html - R. Martinho Fernandes
1
当你到达“邪恶”的单子时,给我打电话吧;-) - R. Martinho Fernandes

2
你程序中的问题在于maximumBy函数似乎存在一个bug,请向GHC团队报告此问题 :)

这是修复后的版本:

maximumByFixed :: (Ord a) => (a -> a -> Ordering) -> [a] -> a
maximumByFixed op (h:t) = step h t
    where
        step v [] = v
        step v (h:t)
            | v `op` h == LT
            = step h t
            | otherwise
            = step v t

关于为什么编译失败,需要像Martinho所说的那样拥有一个“main”函数。话虽如此,ghci只是一个GHC程序,您始终可以运行:
ghci Main.hs +RTS -K128M

当然,由于你的程序运行需要一些时间,因此编译它也不是一个坏主意。你还可以通过添加导出项和更改名称为Main来编译要与GHCI一起使用的模块:

module Chain (longestChain) where

然后运行:

ghc -O2 --make Chain.hs

然后像平常一样运行ghci:

ghci Chain.hs

如果编译对象是最新的,它将自动加载。

1
@bdonlan:在maximumBy的上下文中没有必要使用“Ord a”,因为它应该仅使用提供的比较函数来比较“a”。 - yairchu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接