Monday, 22 January 2007

stupid day

A coding day today, but a stupid one, one of those annoying days where you try to do something simple and it takes you practically forever. I kept getting type errors... good thing too... because it turns out half my understanding of what I was doing was wrong, and I only got the picture once I looked at the types properly. Had to rewrite a bit of code, though to make it do the right thing. I'm basically just hunting down traces in test suites, but it's not entirely simple because I'm looking out for pairs of test cases in a single suite for which there are no differences in the traces... kind of situation I tend to deal with badly, these kinds of boolean inversion things, where you get your Trues and Falses mixed up, or your anys and your alls, or your nones and alls, etc. I dunno, just being stupid. The main issue is just really understanding in detail what it is you're trying to do. I got the big picture, can handle the details, but getting from big picture to details, that's tricky.

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: