Cookbook/Lists: Difference between revisions
< Cookbook
No edit summary |
No edit summary |
||
Line 11: | Line 11: | ||
Furthermore, Haskell supports some neat concepts. | Furthermore, Haskell supports some neat concepts. | ||
=Infinite lists= | = Infinite lists = | ||
<haskell> | <haskell> | ||
Prelude> [1..] | Prelude> [1..] | ||
Line 29: | Line 29: | ||
</haskell> | </haskell> | ||
=List comprehensions= | = List comprehensions = | ||
The list of all squares can also be written in a more comprehensive way, using list comprehensions: | The list of all squares can also be written in a more comprehensive way, using list comprehensions: |
Revision as of 10:52, 23 April 2009
In Haskell, lists are what Arrays are in most other languages. Haskell has all of the general list manipulation functions, see also Data.List
.
head [1,2,3] --> 1
tail [1,2,3] --> [2,3]
length [1,2,3] --> 3
init [1,2,3] --> [1,2]
last [1,2,3] --> 3
Furthermore, Haskell supports some neat concepts.
Infinite lists
Prelude> [1..]
The list of all squares:
square x = x*x
squares = map square [1..]
But in the end, you probably don't want to use infinite lists, but make them finite. You can do this with take
:
Prelude> take 10 squares
[1,4,9,16,25,36,49,64,81,100]
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 ]