Re: Factor

Factor: the language, the theory, and the practice.

Morse Palindromes?

Friday, October 11, 2013

#morse #text

There was a fun post today on Metafilter about the longest palindrome in Morse code being “intransigence” (along with other odd facts).

This jumped out to me for a few reasons:

So, maybe we can confirm that “intransigence” really is the longest palindrome!

palindrome?

The basic definition for a “palindrome” is a word that “reads the same backward as forward”. Given that, it’s easy to build a first version that checks this:

: palindrome? ( str -- ? ) dup reverse = ;

However, in our tutorial we suggest building a more robust version that normalizes the input to handle palindromes such as “A man, a plan, a canal: Panama.”:

: normalize ( str -- str' ) [ Letter? ] filter >lower ;

: palindrome? ( str -- ? ) normalize dup reverse = ;

morse-palindrome?

For our morse code palindrome detector, we need to convert our string to morse code, removing extra spaces that the morse code vocabulary adds between letters, before checking for palindrome-ness:

: normalize-morse ( str -- str' )
    normalize >morse [ blank? not ] filter ;

: morse-palindrome? ( str -- ? )
    normalize-morse dup reverse = ;

The longest word in the dictionary that is a morse palindrome is:

IN: scratchpad "/usr/share/dict/words" ascii file-lines
               [ morse-palindrome? ] filter longest .
"incalescence"

Wait, that isn’t “intransigence”!

Well, no, but “incalescence” has the same number of letters (13) and happens to be slightly longer in morse code. So maybe it’s a tie, or maybe they should update their trivia!

In fact, there are several “longest” morse palindromes:

IN: scratchpad "/usr/share/dict/words" ascii file-lines
               [ morse-palindrome? ] filter all-longest .
{
    "incalescence"
    "intercentral"
    "predestinate"
    "predestitute"
    "protectorate"
    "Raphaelesque"
    "ultranatural"
}

P.S., it looks like “Raphaelesque” might be the longest morse palindrome by morse code length.

P.P.S., for some reason /usr/share/dict/words doesn’t contain the word “intransigence”.