Sunday, December 24, 2006

ROT13 in Haskell

To drive home the point of F#/OCaml lacking some predefined functions that make life easier, here is a version of the same ROT13 encoding algorithm, now in Haskell. Of course the whole thing is easier not only because of functions like zip, take and drop, but also because strings in Haskell are actually lists of characters. Anyway, here it is. Compare with the F# version.

rot13 s = map rotchar s
where rotchar c = maybe '#' id (lookup c transp)
transp = zip letters ((drop 13 letters) ++ (take 13 letters))
letters = ['a' .. 'z']

And now for the use case:

*Rot13> rot13 "feijoada"
"srvwbnqn"

1 comment:

dmwit said...

Sorry, I know this post is a bit old, but you happen to be the first result on Google for "rot13 haskell" just now. =)

Let me suggest this replacement for rotchar above (all the other local bindings look sane enough):
rotchar c = fromMaybe c (lookup c transp)
This definition has the advantage that it doesn't change non-alpha characters into '#'. =) ("fromMaybe" is just a convenient wrapper for "maybe" that's defined in Data.Maybe.)

~d