ROT13 in F#

Over on his blog, Andrei Formiga has a series of post on implementing ROT13 in F# and Haskell.

http://codemiscellany.blogspot.com/2006/12/rot13-in-f.html

http://codemiscellany.blogspot.com/2006/12/rot13-in-haskell.html

http://codemiscellany.blogspot.com/2006/12/rot13-in-f-revisited.html

http://codemiscellany.blogspot.com/2006/12/still-more-rot13.html

 

I like is implementation using library functions that don’t yet exist in F#, such as drop and zip. Here is the implementation itself, stripped of the extra library functions he had to implement, for the original see the above links.

 

#light

let rot13 s =
    let letters = ['a' .. 'z']
    let transp = zip letters ((drop 13 letters) @ (take 13 letters))
    let rotchar c = List.assoc c transp
    strmap rotchar s

 

The clever bit of this implementation is on the 4th line where he uses the functions drop and take to create a rotated list and the function zip to a map between that and the original letter list. While this is an interesting way of implementing this I think there is a way to do this without the need to define extra library functions. So here is my implementation, the same number of lines but more characters!

 

#light

let rot13 (s : string) =    

    let letters = ['a' .. 'z']

    let transp = letters |> List.mapi (fun i l -> l, List.nth letters ((i + 13) % 26))    

    let rotchar c = List.assoc c transp

    new string(s.ToCharArray() |> Array.map rotchar)

 

Bookmark
dotnetkicks+, digg+, reddit+, del.icio.us+, dzone+, facebook+

Print | posted @ Wednesday, December 27, 2006 7:05 AM

Comments on this entry:

No comments posted yet.

Your comment:

(Note: all comments are moderated so it may take sometime to appear)

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 2 and 1 and type the answer here:
 

Links

 Subscribe in a reader
Twitter Follow me on Twitter
FaceBook View my Facebook
LinkedIn View my LinkedIn Profile Viadeo Viadeo Profile (Français)

Badges



Disclaimer

The views expressed on this weblog are mine and do not necessarily reflect the views of my employer.

All postings are provided "AS IS" with no warranties, and confer no rights.

www.flickr.com
This is a Flickr badge showing public photos and videos from Robert Pickering. Make your own badge here.