Revision as of 10:21, 23 April 2009

This article is a draft, with further revisions actively invited. Drafts are typically different than stubs in that these articles are in an active edit process. Feel free to help by expanding the article.

1 Prelude

A lot of functions are defined in the "Prelude". Also, if you ever want to search for a function, based on the name, type or module, take a look at the excellent Hoogle. This is for a lot of people a must-have while debugging and writing Haskell programs.

4.1 Infinite lists

But in the end, you probably don't want to use infinite lists, but make them finite. You can do this with

take

:

Prelude>take10 squares
[1,4,9,16,25,36,49,64,81,100]

4.2 List comprehensions

The list of all squares can also be written in a more comprehensive way, using list comprehensions:

squares =[x*x | x <-[1..]]

List comprehensions allow for constraints as well:

-- multiples of 3 or 5
mults =[ x | x <-[1..],mod x 3==0||mod x 5==0]

5 Other data structures

GHC comes with some handy data-structures by default. If you want to use a Map, use Data.Map. For sets, you can use Data.Set. A good way to find efficient data-structures is to take a look at the hierarchical libraries, see Haskell Hierarchical Libraries and scroll down to 'Data'.

5.1 Map

A naive implementation of a map would be using a list of tuples in the form of (key, value). This is used a lot, but has the big disadvantage that most operations take O(n) time.

offer lookup in constant time but they get copied when you update an element. Use them if they can be filled in one go.
The following example groups a list of numbers according to their residual after division by

are updated in place, but they have to live in the IO-monad or the ST-monad in order to not destroy referential transparency. There are also diff arrays like

Data.Array.Diff.DiffArray i e

that look like immutable arrays but do updates in place if used in a single threaded way. Here is depth first search with diff arrays that checks whether a directed graph contains a cycle. Note: this example really belongs to Map or Set.

6 Pattern matching

Regular expressions are useful in some situations where the Data.List
library is unwieldy. Posix style regular expressions are available in
the core libraries, and a suite of other regular expression libraries
are [also available], including PCRE and TRE-style regexes.