[Haskell-cafe] Line noise

Claus Reinke claus.reinke at talk21.com
Sun Sep 21 16:04:03 EDT 2008


> I posted a snippet of code which included the phrase
> 
>  mapM_ (\(n,v) -> putStrLn $ "[" ++ show n ++ "] = " ++ show v) (zip [0..] vs)

"Don't do that, then"?-) 

 mapM_ putStrLn $
    map (\(n,v) -> "[" ++ show n ++ "] = " ++ show v) 
        (zip [0..] vs)
->
 mapM_ putStrLn $
    map (\(n,v) -> "[" ++ show n ++ "] = " ++ show v) 
        (addIndices vs)
    where addIndices vs = zip [0..] vs
->
 mapM_ putStrLn (map formatPair (addIndices vs))
    where { addIndices vs = zip [0..] vs;
                 formatPair (n,v) = "[" ++ show n ++ "] = " ++ show v }
-> ...
 printList (map formatPair (addIndices vs))
    where { foreach :: [i] -> (i->IO ()) -> IO ();
                 foreach list action = mapM_ action list;

                 printList :: [String] -> IO ();
                 printList strings = foreach strings (\string->putStrLn string);

                 addIndices :: [x] -> [(Integer,x)];
                 addIndices vs = zip [0..] vs;

                 formatPair :: Show x => (Integer,x) -> String
                 formatPair (n,v) = "[" ++ show n ++ "] = " ++ show v }

Add comments (or replace types with comments, if you don't
want to explain type classes), perhaps use an explicit loop instead 
of mapM_, add salt and pepper (or some more parens), check 
for correctness, etc.

Not as cute as the one-liner, but quite possibly easier to read
and explain. Haskell isn't APL - boldly break the line barrier,
if you want to be understood by non-Haskellers. Breaking 
stuff up into digestible pieces, and going more slowly than
necessary, might also help. Once your readers understand
your code, you can add the one-liner and ask for applause
(or show how to derive the one-liner from the long-hand
version if you want to motivate people to read about Haskell).

Just another opinion,
Claus

"Dr., it hurts when I do that."




More information about the Haskell-Cafe mailing list