pairs...
Proof of my Haskell non-mastery... I wrote this piece of code and knew straight away that no, this is NOT Haskell-like. Haskell-like is when (1) there is practically nothing there (2) what little is there is obvious (maybe you have to learn a little Haskell first, but modulo learning Haskell, the ideal code is just immediately apparant, at least to the same extent as the task at hand). The task at hand is to have the cross product of a list with itself... well, half the cross product because you don't want to be redundant:
-- pairs [ a, b, c, d ] == [ (a,b), (a,c), (a,d), (b,c), (b,d), (c,d) ]
pairs :: [a] -> [(a,a)]
Here is the typical way too complicated erician version:
pairs xs = concat $ zipWith (\x ys -> [ (x,y) | y <- ys ]) xs (drop 1 $ tails xs)
Here is the first suggestion from #haskell (with an extra point thrown in for clarity)
pairs [] = []
pairs (x:xs) = map (\y -> (x,y)) xs ++ pairs xs
Apfelmus suggests
pairs xs = concatMap (uncurry zip) $ zip (map repeat xs) (tails $ tail xs)
And the nicest version so far, by glguy
pairs xs = [(a,b) | (a:as) <- tails xs, b <- as]
Yeah, ok, so I'm quibbling over one-or-two liners here, but is is clear that the alternatives proposed are much better as far as clarity goes. This is where programming gets nice, though, when it becomes Go-like. Easy to learn, hard to master.
Anyway, very pleased with the new pastebin (written in Haskell of course).
koan
A little Haskell koan for you... What does this do and why? It took me a while to get it, but when I did, I felt a tiny bit smarter...filterM (\_ -> [False ..])Funny, it made sense an hour ago... now I don't get it anymore [I know what it does, just don't know why anymore]. But it'll come back.

No comments:
Post a Comment