Monday, 22 November 2010

Checking for pangrams

A pangram is a phrase that uses every letter of the alphabet. The following F# function can be used to check a string to see if it constitutes a pangram:

> let isPangram (str: string) = (set['a'..'z'] - set(str.ToLower())).IsEmpty;;
val isPangram : string -> bool

The function works by computing a set difference, removing the set of letters used in the string from the set of letters in the alphabet. If the resulting set is empty then the string must have used every letter in the alphabet and, therefore, it is a pangram.

Note how easy F# makes it to build sets from arbitrary sequences (lists and strings of characters, in this case) and perform set theoretic operations such as set difference (and union and intersection) on them. This basic functionality has a wide variety of applications ranging from the manipulation of strings seen here to the computation of nth-nearest neighbors in computational science (see the article Traversing networks: the nth-nearest neighbor in The F#.NET Journal).

For example, the following verifies a popular English pangram:

> isPangram "The quick brown fox jumped over the lazy dogs";;
val it : bool = true


Michael Robin said...

Ya learn somthin' new every day. I learned it (in typing class :)) as "...the lazy dog's back" - I never bothered to notice that the final word was not needed...

Anonymous said...

Even better: The quick brown fox *jumps* over the lazy *dog*