# Difference between revisions of "Cookbook/Lists"

< Cookbook

Jump to navigation
Jump to search
(content got moved) |
|||

Line 1: | Line 1: | ||

− | In Haskell, lists are what Arrays are in most other languages. Haskell has all of the general list manipulation functions, see also <hask>Data.List</hask>. |
||

− | |||

− | <haskell> |
||

− | 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 |
||

− | </haskell> |
||

− | |||

− | Furthermore, Haskell supports some neat concepts. |
||

− | |||

− | = Infinite lists = |
||

− | <haskell> |
||

− | Prelude> [1..] |
||

− | </haskell> |
||

− | |||

− | The list of all squares: |
||

− | <haskell> |
||

− | square x = x*x |
||

− | squares = map square [1..] |
||

− | </haskell> |
||

− | |||

− | But in the end, you probably don't want to use infinite lists, but make them finite. You can do this with <hask>take</hask>: |
||

− | |||

− | <haskell> |
||

− | Prelude> take 10 squares |
||

− | [1,4,9,16,25,36,49,64,81,100] |
||

− | </haskell> |
||

− | |||

− | = List comprehensions = |
||

− | |||

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

− | |||

− | <haskell> |
||

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

− | </haskell> |
||

− | |||

− | List comprehensions allow for constraints as well: |
||

− | |||

− | <haskell> |
||

− | -- multiples of 3 or 5 |
||

− | mults = [ x | x <- [1..], mod x 3 == 0 || mod x 5 == 0 ] |
||

− | </haskell> |