Originally Posted by
MacNilly
Code:
main = foldr((>>) . putStrLn . show)(return ())([1 .. 10]);
Thats the most ugly code I've ever seen. If I didn't know it prints 1 to 10 then I'd be lost in days of analysis trying to figure it out. Sucks. Whats wrong with just
Also WTF is the return() HAH who ever writes this crap?
4. Weeks.
This took me 4 weeks to figure out lol XD
It is very ugly but let me explain, the foldr signature is :
Code:
foldr :: (a -> b -> b) -> b -> [a] -> b
I'm using `[a]` instead of traversable `t a` for simplicity.
foldr is somewhat intuitive in that it folds from right to left. Using this and the above type signature, we can infer that first part of our fold is
Code:
(>>) . putStrLn . show $ 10
which gives us a partially applied monadic sequence operation. Using the `b` part of our signature, this is then applied to `return ()` which just gives us an empty monad instance.
So basically, what we wind up with is this:
Code:
... (8 >> (9 >> (10 >> IO())))
Remember that
Code:
m >> k = m >>= \_ -> k
for monads.
So you wind up with (let's pretend we don't need the show crap and we're only going 1 through 5):
Code:
putStrLn("1") >> (putStrLn("2") >> (putStrLn("3") >> (putStrLn("4") >> ((putStrLn("5") >> return ())))))
Long-story short, this is why Haskell is stupid and isn't used in the industry and no amount of hipster nonsense (credit to Yarin for the hipster term ;P) can ever hope to make it a practical and viable programming language.
However, learning category theory has done nothing but make me a better programmer.
Edit:
Some of the stuff is just there because Haskell has a decent type system. If we have a number, we need to Show it first and then when we putStrLn, we simply get a monad back out. Because we want to sort of chain these guys together, it's easiest to fold using a sequence which does our >>= stuff for us. Basically, we want to map over the list creating an IO instance of each element and then we want to chain them together. This is most easily expressed as a fold with a monadic sequencing.
Something something functors something something applicative, no one understands my code, god, Mom!