[Haskell-cafe] First time haskell - parse error!

Sebastian Fischer sebf at informatik.uni-kiel.de
Wed Mar 10 05:10:48 EST 2010


On Mar 10, 2010, at 8:47 AM, Ketil Malde wrote:

> I think it is better style to avoid this kind of one-off named
> values.  I much prefer:
>
>         then "Golds "++show (gold s g)++...
>
> For some reason, this is a style isse that doesn't get much attention

At the end of the Section on function composition in the tutorial  
"Learn You a Haskell for Great Good" [1] there is a nice example  
demonstrating that sometimes it may be preferable to introduce names  
for readability:

Quote:
In the section about maps and filters, we solved a problem of finding  
the sum of all odd squares that are smaller than 10,000. Here's what  
the solution looks like when put into a function.

     oddSquareSum :: Integer
     oddSquareSum = sum (takeWhile (<10000) (filter odd (map (^2)  
[1..])))
Being such a fan of function composition, I would have probably  
written that like this:

     oddSquareSum :: Integer
     oddSquareSum = sum . takeWhile (<10000) . filter odd . map (^2) $  
[1..]
However, if there was a chance of someone else reading that code, I  
would have written it like this:

     oddSquareSum :: Integer
     oddSquareSum =
         let oddSquares = filter odd $ map (^2) [1..]
             belowLimit = takeWhile (<10000) oddSquares
         in  sum belowLimit
It wouldn't win any code golf competition, but someone reading the  
function will probably find it easier to read than a composition chain.

End Quote.

[1]: http://learnyouahaskell.com/higher-order-functions#composition



-- 
Underestimating the novelty of the future is a time-honored tradition.
(D.G.)





More information about the Haskell-Cafe mailing list