Version 1.11
Examples:
Haskell list operations, stacks, and queues: ListOps.hs, ListTest.hs, Stack.hs, Queue.hs
A list is a recursive structure. A list is either:
[], the empty list; orhead : tail, where head is the first element of the list, and tail is the rest of the list. Note: head may be any kind of thing; tail is a sublist, therefore a list.The list [a, b, c, d] in head:tail notation:
a : b : c : d : []
What is the head of [1, 2, 3]? the tail? the head of the tail? the tail of the tail? the head of the head (!)?
The recursive structure of lists makes it natural to solve many problems by recursive methods. A few examples:
What is the length of a list (number of elements)?
Find an element t in a list.
Find the sum of a list of numbers.
Lists are equal if ???
Haskell list operations, stacks, and queues:
ghci starts the Haskell interpreter in interactive moderunghc MyFile.hs runs a Haskell scriptghc --make MyFile compiles the Haskell source file MyFile.hs and produces an executable file MyFile. You can then run it with the command ./MyFileIn most programming languages, when you call a function (or method), the expressions given as arguments to the function must be evaluated before the function can begin running. For example, in Java, foo(2, bar(x + 1)), the method foo needs to have the values of 2 and of bar(x + 1) before it can get started.
In Haskell, on the contrary, the evaluation of expressions is deferred until their values are really needed. This is called lazy evaluation. In the example above, if the foo function only uses its second argument when the first argument is greater than 10, then the second argument would never be needed in this case, so it would not be evaluated.
One advantage of lazy evaluation is that it’s possible to work with infinite data structures, as long as you use only finite parts of them. For example, the Haskell expression [1 ..] designates the infinite list of positive integers 1, 2, 3, …. But the list elements are generated only to the extent needed. So if your computation takes only the first 5 elements of the list, it can run.
Prelude> take 5 [1 ..]
[1,2,3,4,5]A disadvantage of lazy evaluation is that it becomes harder to reason about when the values are produced and, consequently, how much memory the program uses.
For more information, read Lazy evaluation on the Haskell Wiki.