next up previous contents
Next: 6.7.6 The function type Up: 6.7 Operators Previous: 6.7.4 The boolean type   Contents


6.7.5 The list type

Lists are created from two constructors. [] denotes the empty list. The list construction operator (:, pronounced CONS by LISP programmers) takes an item and a list, and returns a new list with the item added to the front. As a convenience, nip2 has a syntax for list constants. A list constant is a list of items, separated by commas, and enclosed in square brackets:

                                                      
  12:[] == [12]
  12:13:14:[] == 12:(13:(14:[])) == [12,13,14]
  [a+2,3,4] == (a+2):3:4:[]
  [2]:[3,4] == [[2],3,4]

Use the functions hd and tl to take the head and the tail of a list:

                                                      
  hd [12,13,14] == 12
  tl [12,13,14] == [13,14]

Use .. in a list constant to define a list generator. List generators build lists of numbers for you:

                                                      
  [1..10] == [1,2,3,4,5,6,7,8,9,10]
  [1,3..10] == [1,3,5,7,9]
  [10,9..1] == [10,9,8,7,6,5,4,3,2,1]

List generators are useful for expressing iteration.

Lists may be infinite:

                                                      
  [1..] == [1,2,3,4,5,6,7,8,9 ..]
  [5,4..] == [5,4,3,2,1,0,-1,-2,-3 ..]

Infinite lists are useful for expressing unbounded iteration. See §6.9.

A list may contain any object:

                                                      
  [1,'a',true,[1,2,3]]

Mixing types in a list tends to be confusing and should be avoided. If you want to group a set of diverse objects, define a class instead, see §6.11.

Lists of lists of reals are useful for representing arrays.

As a convenience, lists of characters may be written enclosed in double quotes:

                                                      
  "abc" == ['a','b','c']

You can use the list index operator (?) to extract an element from a position in a list:

                                                      
  [1,2,3] ? 0 == 1
  "abc" ? 1 == 'b'

You can use the list join operator (++) to join two lists together end-to-end.

                                                      
  [1,2,3] ++ [4,5,6] == [1,2,3,4,5,6]


next up previous contents
Next: 6.7.6 The function type Up: 6.7 Operators Previous: 6.7.4 The boolean type   Contents
John Cupitt 2004-12-20