Prolog Tutorial 2

Questions and Answers

  1. A palindrome is a word which is the same backwards as forwards. Write a rule palindrome(List) which succeeds if List is the same backwards as forwards. Test your rule.

    Remember that the built-in predicate name converts an atom into a list of ASCII codes of its characters. This information should enable you to put palindrome into a short program to test a typed in word to see whether it is a palindrome started by a rule pal. Test it with palindromes such as 'ada` and 'madam`.

    The rule to test a palindrome list is amazingly simple:

    palindrome(List) :- reverse(List,List).
    
    where reverse is defined (in your notes) as:
    reverse(L1,L2) :- rev(L1,[],L2).
    rev([],L,L).
    rev([X|L],L2,L3) :- rev(L,[X|L2],L3).
    
    The program to test a palindrome could be:
    pal :- write('Enter your word: '),read(Word),name(Word,List),palindrome(List).
    

  2. Write a rule convert which works through a list of integers, takes all those between 64 and 91, and adds 32 to them. In other words, if the list of integers is a list of ASCII codes, it converts all the ASCII codes of upper case characters to the ASCII codes of their corresponding lower case characters.

    convert([],[]).
    convert([L|Lt],[Q|Qt]) :- L>64, L<91, Q is L+32, convert(Lt,Qt).
    convert([L|Lt],[L|Qt]) :- convert(Lt,Qt).
    

  3. You can put this rule into your program pal

    pal :- write('Enter your word: '),read(Word),name(Word,List),convert(List,NewList),palindrome(NewList).
    

  4. Write a rule stars to draw a specified number of stars or asterisks in a horizontal line on the screen.

    stars(0).
    stars(N) :- write('*'), M is N-1, stars(M).
    

  5. Share prices for a company at the end of each month are saved as facts of the form:

    share(jan,25).
    share(feb,15).
    share(mar,24).
    share(apr,12).
    share(may,30).
    

    Write a rule display which writes these out in two columns on the screen.

    display :- share(Month,Price),write(Month),write(' '),write(Price),nl,fail.
    display.
    

  6. Now modify this rule to call the rule stars and draw the share price as lines of stars on the screen instead of writing the numbers. Somethig like this:

    jan *************************
    feb ***************
    mar ************************
    apr ************
    may ******************************
    

    display :- share(Month,Price),write(Month),write(' '),stars(Price),nl,fail.
    display.
    
    stars(0).
    stars(N) :- write('*'), M is N-1, stars(M).
    



Created and maintained by Chris Gill