Sample LISP Exercises

  1. Write a firstatom function that returns the first atom in a list, regardless of whether the given list is nested or not. For example:
    ( firstatom '(a b c) ) => a
    ( firstatom '((x y z) (a (b)) c) ) => x
    ( firstatom '((((1 a) b) (2 c) d) (3 4 e f) ) => 1
    
  2. Write an allfirsts function takes a single list argument and returns a list containing all leading atoms of the elements in its argument (use firstatom in item 1). For example:
    ( allfirsts '((1 2 3) (a b c) (x y z)) ) => (1 a x)
    ( allfirsts '(a b c) ) => (a b c)
    ( allfirsts '((1 2 3) ((x y) z) a ((4 5)(6) 7 (8 9))) ) => (1 x a 4)
    
  3. Selection sort of a list can be recursively defined as cons-ing the minimum value in the list with (the rest of the list, without the minimum, sorted). Complete the following selection sort implementation in Lisp by implementing a getmin function and a removeelement function. Try selsort on the some examples such as:
    ( selsort '(3 1 4 5 2 6) ) => (1 2 3 4 5 6)
    ( selsort '(100 200 50 32 65 12 84) ) => (12 32 50 65 84 100 200)
    ( selsort '(3 1 4 1 5 6 5 5 1 2 6) ) => (1 1 1 2 3 4 5 5 5 6 6)
    
  4. Write a repeater function that takes a list of lists. Each of the inner lists contains a number and a symbol. The function returns a list of repeating symbols as specified by the inner lists. For example:
    ( repeater '( (3 a) (2 b) ) ) => ( a a a b b )
    ( repeater '( (2 hello) (1 there) (5 x) ) ) => ( hello hello there x x x x x )
    
  5. Write a filter function with two arguments: a number and a list. The function returns a list containing all values in the list argument that are less than or equal to the number. For example:
    ( filter 10 '(20 5 10 25 3 6) ) => ( 5 10 3 6 )
    ( filter 5 '(1 4 9 6 5 6 4 2 1 1 9 8 ) ) => ( 1 4 5 4 2 1 1 )
    
  6. Write a split function with two arguments: a number and a list. The function returns a list of two lists, where the first list in this list contains all numbers that are less than or equal to the number, and the second list contains the rest of the numbers. For example:
    ( split 10 '(20 5 10 25 3 6) ) => ( ( 5 10 3 6 ) ( 20 25 ) )
    ( split 5 '(1 4 9 6 5 6 4 2 1 1 9 8 ) ) => ( ( 1 4 5 4 2 1 1 ) ( 9 6 6 9 8 ) )
    
    Note that the above function is a step towards writing a quick sort function.

  7. This next function is a step towards writing a merge sort function. Write a merge function that takes two lists as arguments and returns a single list. Assume that the arguments are lists of numbers that are already sorted. The list returned is a merged, sorted list. For example:
    ( merge '(1 3 6 8) '(2 4 5 9) ) => ( 1 2 3 4 5 6 8 9 )
    ( merge '(1 2 3 10 20 30 40) '(5 7 9) ) => ( 1 2 3 5 7 9 10 20 30 40 )