Difference between revisions of "Haskell in 5 steps"

From HaskellWiki
Jump to navigation Jump to search
(syntax)
(→‎Write your first parallel Haskell program: add troubleshooting section)
 
(47 intermediate revisions by 21 users not shown)
Line 1: Line 1:
Haskell is a general purpose, purely functional programming language. This page will help you get started as quickly as possible.
+
Haskell is a general purpose, purely functional programming language.
  +
This page will help you get started as quickly as possible.
   
 
__TOC__
 
__TOC__
   
== Why learn Haskell? ==
+
== Install Haskell ==
   
  +
The recommended way to get started with programming Haskell is the [http://hackage.haskell.org/platform/ Haskell Platform]. The Platform comes with GHC, the de-facto standard Haskell compiler, and other tools that will help you program Haskell. The installation should be supported on most operating systems. If you encounter difficulty, feel free to reach out to the [https://www.haskell.org/community/ Haskell community].
John Hughes has written a good essay: [http://www.md.chalmers.se/~rjmh/Papers/whyfp.html Why Functional Programming Matters].
 
   
  +
[http://tryhaskell.org/ Try Haskell] provides a less complete but quicker way to give Haskell a shot.
== Install Haskell ==
 
   
  +
== Start Haskell ==
Haskell, like most other languages, comes in two flavors: batch oriented (''compiler'') and interactive (''interpreter''). An interactive system gives you a command line where you can experiment and evaluate expressions directly, and is probably a good choice.
 
   
  +
If you have installed the Haskell Platform, open a terminal and type '''ghci''' (the name of the executable of the GHC interpreter) at the command prompt. Alternatively, if you are on Windows, you may choose '''WinGHCi''' in the Start menu.
{| class="wikitable"
 
|[http://www.haskell.org/ghc/ GHC]
 
|Compiler and interpreter (GHCi)
 
|Probably the most feature-complete system
 
|-
 
|[http://www.haskell.org/hugs/ Hugs]
 
|Interpreter only
 
|Very portable, and more lightweight than GHC.
 
|}
 
   
  +
<pre>
While both GHC and Hugs work on Windows, Hugs has perhaps the best integration on that platform. There is also information available on [[Mac OS X|installing Haskell software on Mac OS X]].
 
  +
$ ghci
  +
GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help
  +
Loading package base ... linking ... done.
  +
Prelude>
  +
</pre>
   
  +
And you are presented with a prompt. The Haskell system now attentively
== Your first Haskell program ==
 
  +
awaits your input.
   
  +
== Write your first Haskell program ==
Please note that this example will not run in hugs, at least not in version 20050308, because hugs does not support defining functions in command prompt. You have to put your definitions into a source file.
 
----
 
If you've learned to program another language, your first program probably was Hello world. In Haskell, your first program is the Factorial function.
 
   
  +
If you've learned to program another language, your first program
'''1) Start an interpreter'''
 
  +
probably was "Hello, world!", so let's do that:
  +
  +
<haskell>
  +
Prelude> "Hello, World!"
  +
"Hello, World!"
  +
</haskell>
  +
  +
The Haskell system evaluated the string, and printed the result.
  +
Or we can try a variation to print directly to standard output:
  +
  +
<haskell>
  +
Prelude> putStrLn "Hello World"
  +
Hello World
  +
</haskell>
  +
  +
Using a Haskell compiler, such as [http://haskell.org/ghc GHC], you can
  +
compile the code to a standalone executable. Create a source file
  +
'''hello.hs''' containing:
  +
  +
<haskell>
  +
main = putStrLn "Hello, World!"
  +
</haskell>
  +
  +
And compile it with:
   
Open a terminal. If you installed GHC type '''ghci''' (the GHC interpreter). If you installed Hugs type '''hugs'''.
 
 
<pre>
 
<pre>
  +
$ ghc -o hello hello.hs
$ ghci
 
  +
</pre>
___ ___ _
 
/ _ \ /\ /\/ __(_)
 
/ /_\// /_/ / / | | GHC Interactive, version 6.4, for Haskell 98.
 
/ /_\\/ __ / /___| | http://www.haskell.org/ghc/
 
\____/\/ /_/\____/|_| Type :? for help.
 
   
  +
You can then run the executable ('''./hello''' on Unix systems, '''hello.exe''' on Windows):
Loading package base-1.0 ... linking ... done.
 
  +
Prelude>
 
  +
<pre>
  +
$ ./hello
  +
Hello, World!
 
</pre>
 
</pre>
   
  +
== Haskell the calculator ==
'''2) Write your first program'''
 
  +
  +
Let's do something fun. In Haskell, your first true program is the
  +
factorial function. So back to the interpreter now and let's define it:
   
From GHCi, we can either load programs from files, or we can define them directly at the command promt. Try the following:
 
 
<haskell>
 
<haskell>
 
Prelude> let fac n = if n == 0 then 1 else n * fac (n-1)
 
Prelude> let fac n = if n == 0 then 1 else n * fac (n-1)
 
</haskell>
 
</haskell>
This defines a function called '''fac''' which computes the factorial of an integer (see step 4 for details).
 
   
  +
This defines a new function called '''fac''' which computes the
'''3) Run it'''
 
  +
factorial of an integer.
   
Type '''fac 12''' to pass the argument 12 to the function '''fac'''.
+
We can now run '''fac''' on some argument:
 
<haskell>
 
<haskell>
*Main> fac 12
+
Prelude> fac 42
  +
1405006117752879898543142606244511569936384000000000
479001600
 
 
</haskell>
 
</haskell>
'''Congratulations!''' You've successfully run your first Haskell program.
 
   
  +
'''Congratulations!''' Programming made easy. Note that if you're using
=== But I want Hello World! ===
 
  +
Hugs, you'll need to load the definition of '''fac''' from a file,
 
  +
'''fac.hs''', containing:
Before venturing into the long explanation, here is Hello World:
 
   
 
<haskell>
 
<haskell>
  +
fac n = if n == 0 then 1 else n * fac (n-1)
putStrLn "Hello World"
 
 
</haskell>
 
</haskell>
   
  +
And run it with Hugs as follows (this also works in GHCi):
Typing this into GHCi will give you the result you expector at least, the result you should be expecting.
 
   
  +
<haskell>
If you want an executable that prints the magic string when it is executed, you can put the following in a file called '''hello.hs''':
 
  +
Hugs.Base> :load fac.hs
  +
Main> fac 42
  +
1405006117752879898543142606244511569936384000000000
  +
</haskell>
  +
  +
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):
   
 
<haskell>
 
<haskell>
  +
fac 0 = 1
main = putStrLn "Hello World"
 
  +
fac n = n * fac (n-1)
  +
  +
main = print (fac 42)
 
</haskell>
 
</haskell>
   
  +
which can then be compiled and run:
The compiler requires a value called '''main''', so it knows what to execute. Compile it with '''ghc hello.hs -o hello''' and run the resulting executable ('''./hello''' on Unix, '''hello.exe''' on Windows).
 
   
  +
<pre>
=== Making a Short Story Long ===
 
  +
$ ghc -o fac fac.hs
  +
$ ./fac
  +
1405006117752879898543142606244511569936384000000000
  +
</pre>
   
  +
'''Great!'''
One interesting aspect of functional programming is that we are working with ''functions''. Functions don't have side
 
effects, they return a value that depends on the parameters. In order to do IO (say, printing out messages), you could imagine functions taking a parameter '''world''' encompassing all external state, and returning a modified '''world''' (one with the words Hello World on your monitor), which in turn can be passed on to subsequent functions.
 
   
  +
===Write your first parallel Haskell program===
Haskell provides something similar, but more convenient: it treats functions that interact with the world as a separate type, often called ''IO actions''. So while a function converting a number to its printed representation can have type '''Int -> String''', a function reading a string with a specific length from the terminal will probably have type '''Int -> IO String'''. This means that, given an '''Int''', it returns an ''IO action'' for reading a '''String'''. Hopefully, this explains why '''main''' has type '''IO ()''' -- you generally want your program to be able to interact with the world, and thus it must itself be an IO action.
 
   
  +
Haskell has good support for parallel and multicore programming. We can write a parallel program by adding `par` to expressions, like so:
This may sound complicated, but it isn't all that different from other languages that separate ''statements'' from ''expressions'', and the advantage is that Haskell has a solid framework for working with this, namely the '''IO Monad'''.
 
   
  +
<haskell>
If you'd like a quick introduction to how IO works in Haskell, please have a look at [[Introduction to IO]].
 
  +
import Control.Parallel
   
  +
main = a `par` b `par` c `pseq` print (a + b + c)
== Where to go from here ==
 
  +
where
  +
a = ack 3 10
  +
b = fac 42
  +
c = fib 34
   
  +
fac 0 = 1
There are quite a few good Haskell tutorials and books. Here are some we recommend:
 
  +
fac n = n * fac (n-1)
   
  +
ack 0 n = n+1
'''Tutorials'''
 
  +
ack m 0 = ack (m-1) 1
* [http://www.cs.utah.edu/~hal/ Yet Another Haskell Tutorial] (English)
 
  +
ack m n = ack (m-1) (ack m (n-1))
* [ftp://ftp.geoinfo.tuwien.ac.at/navratil/HaskellTutorial.pdf Haskell-Tutorial] (English)
 
* [http://www.haskell.org/tutorial/ A Gentle Introduction to Haskell] (English)
 
* [http://www.informatik.uni-bonn.de/~ralf/teaching/Hskurs_toc.html Haskell Kurs] (Deutsch)
 
   
  +
fib 0 = 0
'''Courses'''
 
  +
fib 1 = 1
* [http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/external.html Programming in Haskell] (English)
 
  +
fib n = fib (n-1) + fib (n-2)
* Functional programming ([http://www.cs.uu.nl/~jeroen/courses/fp-eng.pdf English], [http://www.cs.uu.nl/~jeroen/courses/fp-sp.pdf Español], [http://www.cs.uu.nl/~jeroen/courses/fp-nl.pdf Netherlands]) (Note, that this uses an old version of Haskell; e.g. input/output has changed since then)
 
  +
</haskell>
   
  +
Compiling with -threaded and optimizations on:
'''References'''
 
* [http://www.cs.uu.nl/~afie/haskell/tourofsyntax.html Tour of Haskell Syntax]
 
* [http://zvon.org/other/haskell/Outputglobal/index.html Haskell Reference]
 
* [http://www.cs.uu.nl/~afie/haskell/tourofprelude.html Tour of the Haskell Prelude]
 
* [http://members.chello.nl/hjgtuyl/tourdemonad.html A tour of the Haskell Monad functions]
 
   
  +
<pre>
'''Textbooks'''
 
  +
$ ghc -O2 --make A.hs -threaded -rtsopts
* [http://www.haskell.org/soe The Haskell School of Expression]
 
  +
[1 of 1] Compiling Main ( A.hs, A.o )
* [http://www.cs.ukc.ac.uk/people/staff/sjt/craft2e/ Haskell: The Craft of Functional Programming]
 
  +
Linking A ...
* [http://www.prenhall.com/allbooks/ptr_0134843460.html Introduction to Functional Programming using Haskell]
 
  +
</pre>
* [http://books.cambridge.org/0521277248.htm An Introduction to Functional Programming Systems Using Haskell]
 
* [http://www.iro.umontreal.ca/~lapalme/Algorithms-functional.html Algorithms: A functional programming approach]
 
* [http://homepages.cwi.nl/~jve/HR/ The Haskell Road to Logic, Maths and Programming]
 
   
  +
''Note that in versions of GHC prior to GHC 7, you can leave off the -rtsopts flag''
For more, see [[Learning Haskell]] and [[Books and tutorials]].
 
   
  +
And now we can run our multicore program. Here across two cores:
== Get help ==
 
   
  +
<pre>
If you have questions, join the [http://haskell.org/mailman/listinfo/haskell-cafe Haskell-Cafe mailing list] or the [[IRC channel]] and ask. You can also ask questions here on the wiki, see [[Questions and answers]].
 
  +
$ time ./A +RTS -N2
  +
1405006117752879898543142606244511569936384005711076
  +
./A +RTS -N2 2.14s user 0.02s system 149% cpu 1.449 total
  +
</pre>
   
  +
Congratulations! You are now programming your multicore!
Information about Haskell support for various operating systems is [http://www.haskell.org/haskellwiki/Category:OS here].
 
  +
  +
==== Troubleshooting ====
  +
  +
If you encounter a <code>Could not find module ‘Control.Parallel’</code> error, please install the parallel library with <code>cabal install --lib parallel</code>
  +
  +
== Where to go from here ==
  +
  +
There are many good Haskell tutorials and books. Here are some we recommend:
  +
  +
'''Tutorials'''
  +
* [http://book.realworldhaskell.org/ Real World Haskell]
  +
* [[Learn_Haskell_in_10_minutes|Haskell in 10 minutes]]
  +
* [http://web.archive.org/web/20090306064337/http://darcs.haskell.org/yaht/yaht.pdf Yet Another Haskell Tutorial] (English)
  +
* [http://www.haskell.org/tutorial/ A Gentle Introduction to Haskell] (English, [[Image:GentleFR.pdf|French PDF]])
  +
* [http://learnyouahaskell.com/ Learn You A Haskell For Great Good!]
  +
  +
For a complete list of textbooks, references and tutorials:
  +
  +
* [[Books and tutorials]]
  +
  +
'''Join the community!'''
  +
  +
Talk to others in the Haskell [[User_groups|community]].
   
 
[[Category:Tutorials]]
 
[[Category:Tutorials]]
  +
  +
Languages: [[Haskell in 5 Schritten|de]] [[5 adımda Haskell|tur]] [[Cn/Haskell 入门五步走|zh/cn]] [[Tw/Haskell入門的5個步驟|zh/tw]] [[Haskell入門 5ステップ|ja]]

Latest revision as of 22:17, 16 December 2020

Haskell is a general purpose, purely functional programming language. This page will help you get started as quickly as possible.

Install Haskell

The recommended way to get started with programming Haskell is the Haskell Platform. The Platform comes with GHC, the de-facto standard Haskell compiler, and other tools that will help you program Haskell. The installation should be supported on most operating systems. If you encounter difficulty, feel free to reach out to the Haskell community.

Try Haskell provides a less complete but quicker way to give Haskell a shot.

Start Haskell

If you have installed the Haskell Platform, open a terminal and type ghci (the name of the executable of the GHC interpreter) at the command prompt. Alternatively, if you are on Windows, you may choose WinGHCi in the Start menu.

    $ ghci
    GHCi, version 6.12.3: http://www.haskell.org/ghc/  :? for help
    Loading package base ... linking ... done.
    Prelude>

And you are presented with a prompt. The Haskell system now attentively awaits your input.

Write your first Haskell program

If you've learned to program another language, your first program probably was "Hello, world!", so let's do that:

Prelude> "Hello, World!"
"Hello, World!"

The Haskell system evaluated the string, and printed the result. Or we can try a variation to print directly to standard output:

Prelude> putStrLn "Hello World"
Hello World

Using a Haskell compiler, such as GHC, you can compile the code to a standalone executable. Create a source file hello.hs containing:

main = putStrLn "Hello, World!"

And compile it with:

    $ ghc -o hello hello.hs

You can then run the executable (./hello on Unix systems, hello.exe on Windows):

    $ ./hello
    Hello, World!

Haskell the calculator

Let's do something fun. In Haskell, your first true program is the factorial function. So back to the interpreter now and let's define it:

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!

Write your first parallel Haskell program

Haskell has good support for parallel and multicore programming. We can write a parallel program by adding `par` to expressions, like so:

import Control.Parallel

main = a `par` b `par` c `pseq` print (a + b + c)
    where
        a = ack 3 10
        b = fac 42
        c = fib 34

fac 0 = 1
fac n = n * fac (n-1)

ack 0 n = n+1
ack m 0 = ack (m-1) 1
ack m n = ack (m-1) (ack m (n-1))

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

Compiling with -threaded and optimizations on:

$ ghc -O2 --make A.hs -threaded -rtsopts
[1 of 1] Compiling Main             ( A.hs, A.o )
Linking A ...

Note that in versions of GHC prior to GHC 7, you can leave off the -rtsopts flag

And now we can run our multicore program. Here across two cores:

$ time ./A +RTS -N2
1405006117752879898543142606244511569936384005711076
./A +RTS -N2  2.14s user 0.02s system 149% cpu 1.449 total

Congratulations! You are now programming your multicore!

Troubleshooting

If you encounter a Could not find module ‘Control.Parallel’ error, please install the parallel library with cabal install --lib parallel

Where to go from here

There are many good Haskell tutorials and books. Here are some we recommend:

Tutorials

For a complete list of textbooks, references and tutorials:

Join the community!

Talk to others in the Haskell community.

Languages: de tur zh/cn zh/tw ja