Exercises Tutorial 4

  1. Write a procedure that will take a list and print out any integers in the top level of the list ( i.e. ignores integers in embedded lists ). This procedure will be called read_int/1. It should work like this:
  2. read_int( [ a, b, 1, 2, [ 3, 4], 5 ] ).

    1

    2

    5

    This first procedure will look something like this…

    read_int( [ ] ). % Stop when the list is empty

    % If the element is an integer print it…

    read_int( [ H | T ] ) :-

    integer( H ),

    nl, write( H ),

    read_int( T ).

    % Otherwise move onto the next element

    read_int( [ H | T ] ) :-

    read_int( T ).

  3. Write a procedure, read_int2/1, which does print out integers in embedded lists. So it should work like this:

read_int( [ a, b, 1, 2, [3, 4], 5 ] ).

1

2

3

4

5

The second procedure will look something like this…

read_int2( [ ] ).

read_int2( [ H | T ] ) :-

integer( H ).

nl, write( H ),

read_int2( T ).

read_int2( [ H | T ] ) :-

is_list( H ),

read_int2( H ),

read_int2( T ).

read_int2( [ H | T ] ) :-

read_int2( T ).