我的第一個Haskell程序

今天下午寫了一個Haskell的hello world,結果不能運行:

module test(main) where
import System.IO

data Shape = Circle Float Float Float | Rectangle Float Float Float Float
surface :: Shape -> Float
surface (Circle _ _ r) = pi * r ^ 2
surface (Rectangle a b c d) = (a-c) * (b-d)
main :: IO()
main = do
print $ surface $ Circle 2.2 3.0 2.5
print $ surface $ Rectangle 1 2 4 9

編譯報錯

ghc -o test test.hs

test.hs:1:8: parse error on input ‘test’

貌似是因爲module名字首字母要大些。
改了之後,在運行。還是有問題,這次是警告。
[quote]
ghc -o test test.hs
[1 of 1] Compiling Test ( test.hs, test.o )
Warning: output was redirected with -o, but no output will be generated
because there is no Main module.
[/quote]
我比較了網上的hello world例子發現,和我的不同之處在於它的沒有定義module。
去掉module那行試一下
[quote]
[1 of 1] Compiling Main ( test.hs, test.o )
Linking test ...
[/quote]
這次正常了。
運行:
[quote]
./test
19.634954
21.0
[/quote]

最終版本的代碼:

import System.IO

data Shape = Circle Float Float Float | Rectangle Float Float Float Float
surface :: Shape -> Float
surface (Circle _ _ r) = pi * r ^ 2
surface (Rectangle a b c d) = (a-c) * (b-d)
main :: IO()
main = do
print $ surface $ Circle 2.2 3.0 2.5
print $ surface $ Rectangle 1 2 4 9
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章