In today’s Programming Praxis exercise we have to implement the soundex algorithm for encoding people’s last names. Let’s get started, shall we?

Some imports:

import Data . Char import Data . List

The algorithm itself is not all that complicated. My only mistake was that I failed to account for names where the second letter was equal to the first, such as Lloyd, since initially I only grouped after removing the first letter.

soundex :: String -> String soundex = f . map head . group . map toUpper where f [] = [] f ( x : xs ) = x : take 3 [ toNum c | c <- xs ++ repeat ' 0 ', notElem c "AEHIOUWY" ] toNum c = maybe ' 0 ' snd . find ( elem c . fst ) $ zip ( words "BFPV CGJKQSXZ DT L MN R" ) [' 1 '..]

A test to see if everything is working correctly:

main :: IO () main = do test [ "Euler" , "Gauss" , "Hilbert" , "Knuth" , "Lloyd" , "Lukasiewicz" ] test [ "Ellery" , "Ghosh" , "Heilbronn" , "Kant" , "Ladd" , "Lissajous" ] where test xs = print $ map soundex xs == result result = [ "E460" , "G200" , "H416" , "K530" , "L300" , "L222" ]

Yup, and at only about a third the size of the Scheme solution I’d say that’s not bad.

Share this: Twitter

Facebook

Like this: Like Loading... Related

Tags: bonsai, code, Haskell, kata, last, name, praxis, programming, soundex