
-----------------------------------
wtd
Fri Nov 19, 2004 5:07 am

[Haskell-tut] Lists
-----------------------------------
Recap

We have integers, floating point numbers, characters, and strings. 

What's new?

Lists are collections of a single type of data.

What does a list look like?

A simple list of integers looks like:

[1, 2, 3, 4]

Of course, a simple range like this can be more succinctly represented as:

[1 .. 4]

How is a list defined?

This really deals with the very first operator/function we'll see for dealing with lists.

1 : [2, 3, 4]

Yields:

[1, 2, 3, 4]

So, really, we can rewrite that as:

1 : 2 : 3 : 4 : []

[]

Of course, is an empty list.

That's nice, but...

Lists are roughly analogous to arrays in other languages, and there are similar operations available.

Finding the length of a list:

length ["hello", "world"]

Getting the first element:

head [42.3, 57.6, 98.2]

Getting everything else:

tail [42.3, 57.6, 98.2]

Adding two lists together:

[1, 2, 3] ++ [4, 5]

Finding any element in a list (in this case, the 3rd):

[1 .. 5] !! 2

Finding if an element is in a list:

elem "foo" ["foo", "bar", "baz"]

Or, using the infix form of any function which takes two arguments:

"foo" `elem` ["foo", "bar", "baz"]

Which should read as "is foo an element of this list".

Now, if we want to apply a function to each element in a list, to square each:

(** 2) `map` [1 .. 6]

Or say we want to filter a list:

(> 2) `filter` [1 .. 4]

Another look at the last two

Haskell offers a special bit of syntactic sugar for list operations, called the list comprehension.  Python borrowed this feature.

Squaring 1 through 6 can look like:

[x ** 2 | x 