Haskell is making a real strong bid to wrestle the coveted title of “Brian’s Favorite Language” away from the current title holder (Ocaml, in case you haven’t guessed).
The thing that just happened was that I wanted to find some pythogorean triples- you know, groups of three numbers x, y, and z such that x2 + y2 = z2. So, without really knowing the language in any sort of deep way, and without thinking about it too much, I wrote the quick program:
f :: Int -> [ (Int, Int, Int) ]
f n = [ (x, y, z) |
x <- [ 1 .. n ],
y <- [ x+1 .. n ],
z <- [ y+1 .. n ],
(x * x) + (y * y) == (z * z) ]
You basically don’t even need to know a lick of Haskell to figure out what it does- anyone who’s gotten far enough in math to have encountered sets would probably guess correctly. Well, they might use the term “set” instead of “list”. The fact that it’s returning pythagorean triplets would be blatantly obvious. OK, so it’s an O(N3) algorithm, and you could probably do it in O(N2). When calling it with small numbers, who cares? I can find out that f 20 is [(3,4,5),(5,12,13),(6,8,10),(8,15,17),(9,12,15),(12,16,20)] so fast that I don’t see the computer pause, and that’s the answer I was looking for. And it’s hard to beat this code for succinctness and clarity.
Related posts:
Pingback: Drinkable Chicken » Cool listcomp