2009-08-06 53 views
4

好了,從my previous question我已經結束了與下面的代碼下面就:運行一個編譯好的Haskell程序;得到錯誤

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。

回答

8

要在Haskell中編譯可執行文件,您需要定義一個名爲main的函數。像這樣的東西:

main = print longestChain 

在主模塊的任何地方。

檢查出GHC documentationghc --make

+0

謝謝,你是救命的人。由於你的幫助,我在Haskell的技能已經大大提高。 – 2009-08-06 13:53:46

+3

順便說一句,我注意到你仍然在向這些[]事物調用數組。 GHC中有數組,但它們與*列表*不一樣。它有助於使用正確的術語。如果你想了解不同之處:http://www.cs.auckland.ac.nz/references/haskell/haskell-intro-html/arrays.html和http://www.haskell.org/tutorial/goodies .html – 2009-08-06 14:04:41

+1

當你到達「邪惡」monad時打電話給我;-) – 2009-08-06 14:12:21

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說。這就是說,ghci的只是一個GHC程序,你總是可以運行:

ghci Main.hs +RTS -K128M 

當然,因爲你的程序需要相當長一段時間的運行,它不是一個壞主意,反正編譯它。您也可以編譯與GHCI使用的模塊通過增加出口,改變從主名稱:

module Chain (longestChain) where 

然後運行:

ghc -O2 --make Chain.hs 

然後運行GHCI正常:

ghci Chain.hs 

如果它是最新的,它將自動加載編譯對象。

+0

修復了一個很小(但很重要!)的錯誤,哎呀。 – bdonlan 2009-08-06 14:06:32

+1

@bdonlan:在maximumBy的上下文中不需要「Ord a」,因爲它只應該使用提供的比較函數比較「a」。 – yairchu 2009-08-06 23:28:54

相關問題