Updated 2007-06-28 11:14:13 by LV

if 0 {Richard Suchenwirth 2003-07-16 - Palindromes are strings that read the same from left to right and right to left. Single letters like "I" are trivial palindromes, there are number palindromes like 2002 and names like Anna, Otto, Hannah, but longer strings are more fun to play with. A famous longer palindrome goes
  A man, a plan, a canal - Panama!

(I've always liked, "Go hang a salami; I'm a lasagna hog!" - CLN)

Note that case, punctuation and spaces can be disregarded.

Here's a little toy/tool to experiment with palindromes. Every time you change the entry on top, the bottom text widget is updated to an uppercase palindrome. (When done, you might edit the text for better spaces etc.) }
 package require Tk
 proc main {} {
    entry .e -textvar input
    text .t -width 40 -height 5 -wrap word
    pack .e .t -fill x
    trace var ::input w showPalindrome
 }
 proc showPalindrome {- - -} {
    .t delete 1.0 end
    .t insert end [palindrome [string toupper $::input]]
 }

if 0 {The mirroring of a string happens here - recursively, the first character of the input is placed both to front and end of the result:}
 proc palindrome s {
    if [string length $s] {
       set c [string index $s 0]
       return $c[palindrome [string range $s 1 end]]$c
    }
 }

if 0 {Note that no else branch is needed - if returns an empty string if no branch fired, and a proc returns the last result by default.}
 main
 bind . <Return> {exec wish $argv0 &; exit}

if 0 {Experimenting, we find that any input can produce two palindromes, depending on whether the last letter is duplicated or not - e.g. AN could make ANA or ANNA. The code above does only the latter. But most natural-language examples in Martin Gardner's "Mathematical Circus" are odd-length and hence don't duplicate the last input letter. So maybe the following variant is more useful:}
 proc palindrome s {
    if {[string length $s]>1} {
       set c [string index $s 0]
       return $c[palindrome [string range $s 1 end]]$c
    } else {set s}
 }

VI 2003-11-16. An even longer one is at [1]

Category Toys