Difference between revisions of "Cn/Haskell in 5 steps"
Wangzhifen (talk | contribs) |
Wangzhifen (talk | contribs) |
||
Line 100: | Line 100: | ||
--> |
--> |
||
Haskell 系统对此字符串求值,并输出结果。 |
Haskell 系统对此字符串求值,并输出结果。 |
||
− | + | 稍加修改,可以直接输出到标准输出: |
|
Revision as of 09:20, 14 December 2007
Haskell 是一门通用型纯粹函数式编程语言。 此篇将引导你尽快上路。
安装 Haskell
类似其他语言,Haskell 提供了两种风格的处理方式:批处理(“编译器”)和交互式(“解释器”)。 其中解释器可直接用于测试和计算,是初学者的好帮手。
GHC | 编译器和解释器(GHCi) | 可能是特性实现最全面的系统 |
Hugs | 解释器 | 高度可移植,轻量级 |
GHC 和 Hugs 都可以在 Windows 上工作,Hugs 似乎和此平台配合得更好。 在 Mac OS X 上安装 Haskell。
运行 Haskell
启动一个终端。 如果安装了 GHC,在命令行输入 ghci (GHC 解释器的可执行文件名)。 如果安装了 Hugs,输入 hugs。
$ ghci ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.4, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base-1.0 ... linking ... done. Prelude>
现在你看到一个提示符,Haskell 系统期候你的输入。
第一个 Haskell 程序
如果学习过其他编程语言,你的第一个程序可能就是 "Hello, world!"。我们可以这样:
Prelude> "Hello, World!"
"Hello, World!"
Haskell 系统对此字符串求值,并输出结果。 稍加修改,可以直接输出到标准输出:
Prelude> putStrLn "Hello World"
Hello World
通过 Haskell 编译器,如 GHC,可以把代码编译成单独的可执行档。 新建源文件 hello.hs,包含:
main = putStrLn "Hello, World!"
编译之:
$ ghc -o hello hello.hs
运行之(Unix 系统上用 ./hello,Windows 系统用 hello.exe):
$ ./hello Hello, World!
Haskell 计算器
Let's do something fun. 你的第一个真正的程序是阶乘函数。回到解释器,定义之:
Prelude> let fac n = if n == 0 then 1 else n * fac (n-1)
This defines a new function called fac which computes the factorial of an integer.
We can now run fac on some argument:
Prelude> fac 42
1405006117752879898543142606244511569936384000000000
Congratulations! Programming made easy. Note that if you're using Hugs, you'll need to load the definition of fac from a file, fac.hs, containing:
fac n = if n == 0 then 1 else n * fac (n-1)
And run it with Hugs as follows (this also works in GHCi):
Hugs.Base> :load fac.hs
Main> fac 42
1405006117752879898543142606244511569936384000000000
We can of course compile this program, to produce a standalone executable. In the file fac.hs we can write (and let's use elegant pattern matching syntax just for fun):
fac 0 = 1
fac n = n * fac (n-1)
main = print (fac 42)
which can then be compiled and run:
$ ghc -o fac fac.hs $ ./fac 1405006117752879898543142606244511569936384000000000
Great!
Where to go from here
There are many good Haskell tutorials and books. Here are some we recommend:
Tutorials
- Haskell in 10 minutes
- Yet Another Haskell Tutorial (English)
- A Gentle Introduction to Haskell (English, File:GentleFR.pdf)
For a complete list of textbooks, references and tutorials:
Join the community!
Talk to others in the Haskell community: