我的第一个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名字首字母要大些。
改了之后,在运行。还是有问题,这次是警告。
引用

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.

我比较了网上的hello world例子发现,和我的不同之处在于它的没有定义module。
去掉module那行试一下
引用

[1 of 1] Compiling Main             ( test.hs, test.o )
Linking test ...

这次正常了。
运行:
引用

./test
19.634954
21.0


最终版本的代码:
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

猜你喜欢

转载自messi-18.iteye.com/blog/2199363