6.20 Example: Testing for Palindromes
In this section we define a function pal? that tests whether its
palindrome argument is a palindrome, that is, something
that reads the same backwards and forwards. For example, the string
``Madam I'm Adam'' is a palindrome (excluding blanks and punctuation)
and so is the number . The definition works for any
datatype that has components that are accessed by the indices
.
Here is the definition for pal?. It is simply a call to an
auxiliary function called palAux?. We are following the
convention of ending a function's name with ? if the function
returns a Boolean value.
pal? s == palAux?(s,1,#s)
Type: Void
Here is palAux?. It works by comparing elements that are
equidistant from the start and end of the object.
palAux?(s,i,j) ==
j > i =>
(s.i = s.j) and palAux?(s,i+1,i-1)
true
Type: Void
Try pal? on some examples. First, a string.
Compiling function palAux? with type (String,Integer,Integer) ->
Boolean
Compiling function pal? with type String -> Boolean
Type: Boolean
A list of polynomials.
Compiling function palAux? with type (List Polynomial Integer,
Integer,Integer) -> Boolean
Compiling function pal? with type List Polynomial Integer -> Boolean
Type: Boolean
A list of integers from the example in the last section.
Compiling function palAux? with type (List PositiveInteger,Integer,
Integer) -> Boolean
Compiling function pal? with type List PositiveInteger -> Boolean
Type: Boolean
To use pal? on an integer, first convert it to a string.
Type: Boolean
Compute an infinite stream of decimal numbers, each of which is an
obvious palindrome.
ones := [reduce(+,[10**j for j in 0..i]) for i in 1..]
|
Type: Stream PositiveInteger
How about their squares?
squares := [x**2 for x in ones]
|
Type: Stream PositiveInteger
Well, let's test them all.
[pal?(x::String) for x in squares]
|
Type: Stream Boolean