
Brandon S. Allbery KF8NH wrote:
On May 27, 2007, at 17:23 , Andrew Coppin wrote:
Personally, I try to avoid ever using list comprehensions. But every now and then I discover an expression which is apparently not expressible without them - which is odd, considering they're only "sugar"...
They are. But they're sugar for monadic operations in the list monad, so you have to use (>>=) and company to desugar them. [x | filter even x, x <- [1..10]] becomes do { x <- [1..10]; return (filter even x) } becomes ([1..10] >>= return . filter even).
(Aren't you glad you asked?)
Mmm... LOL! Actually, I recently read something in a book called The Fun of Programming. It basically explains how to implement Prolog in Haskell, including presenting an extremely inefficient way to factorise integers: factors n = do x <- [1..100] y <- [1..100] if x * y == n then return (x,y) else [] I should point out that desugaring do-blocks is possibly one of the hardest things for a Haskell newbie to figure out, but I think I've mastered it now. What we actually have above is factors n = [1..100] >>= \x -> [1..100] >>= \y -> if x * y == n then [(x,y)] else [] which makes it quite clear why "x <- [1..100]" actually causes x to range over all the numbers in the list. (That's the great thing about monads - sometimes it can be hard to wrap your mind around what they actually do when used in nontrivial ways...) Of course, the book explains how to write a new monad that allows infinite lists to be used, and yet still find all factors in finite time. (This involves the Evil ******* Function From Hell I mentioned a while ago.) And then they go on to explain how to implement unification - something I would never have worked out in a million years. And after reading the whole chapter, finally I understand how it is possible for Prolog to exist, even though computers aren't intelligent... Then again, later on in the very same book there's a chapter entitled "Fun with Phantom Types", which made precisely no sense at all... (I find this a lot with Haskell. There is stuff that is clearly written, fairly easily comprehensible, and extremely interesting. And then there's stuff that no matter how many times you read it, it just makes no sense at all. I'm not sure exactly why that is.)