In my last post I showed how to decode morse code in Python using list comprehensions. In this post I will show how to do it in F# instead.
First using list comprehensions:
let codes =
[("A",".-"); ("B","-..."); ("C","-.-."); ("D","-.."); ("E",".");
("F","..-."); ("G","--."); ("H","...."); ("I",".."); ("J",".---");
("K","-.-"); ("L",".-.."); ("M","--"); ("N","-."); ("O","---");
("P",".--."); ("Q","--.-"); ("R",".-."); ("S","..."); ("T","-");
("U","..-"); ("V","...-"); ("W",".--"); ("X","-..-");("Y","-.--");
("Z","--..")]
let rec decode input =
if input = "" then [""]
else [ for c, code in codes when input.StartsWith(code)
for rest in decode(input.Substring(String.length code))
-> c + rest ]
As it can be seen the code is almost identical to the Python code. Incidentally, I could not find a function equivalent to Python’s startswith method in the O’Caml standard library (without using regular expressions). Fortunately F# came with one from the .NET library.
Much to my the surprise the compiled F# (running on Mono 1.2.4) is 4 times slower that the Python code. I then rewrote the program to use sequence comprehensions:
let rec decode input =
if input = "" then { -> "" }
else { for c, code in codes when input.StartsWith(code)
for rest in decode(input.Substring(String.length code))
-> c + rest }
This version runs faster, and uses only a constant amount of memory. Still the Python version is three and half times faster.
I then tried to run the programs on an other computer with Microsoft’s .NET implementation. This improved the F# running times a lot. However, they are still 40% to 80% slower than the Python version.

My current guess is that Python is much better at handling strings than .NET.
The actual numbers:
| Linux, Mono | Vista, MS .NET | |||
|---|---|---|---|---|
| Program | Time sec |
Ratio | Time sec |
Ratio |
morse.py |
7.94 ± 0.05 | 1 | 11.03 ± 0.03 | 1 |
morse.fs |
33.07 ± 0.19 | 4.17 | 19.65 ± 0.33 | 1.78 |
morse-seq.fs |
28.1 ± 0.59 | 3.54 | 16.12 ± 0.36 | 1.46 |
Update 2007-11-12 Added test files:
- Python code:
morse.py - F# code using list comprehensions:
morse.fs - F# code using sequence comprehensions:
morse-seq.fs

Recent Comments