[Haskell-cafe] Is this haskelly enough?

Bjorn Bringert bringert at cs.chalmers.se
Tue Jul 17 19:10:55 EDT 2007


On Jul 18, 2007, at 1:00 , Dan Weston wrote:

> Bjorn Bringert wrote:
>> import Data.List
>> maxsubarrays xs = maximumBy (compare `on` sum)
>>   [zs | ys <- inits xs, zs <- tails ys]
>
> I love this solution: simple, understandable, elegant.
>
> As a nit, I might take out the ys and zs names, which obscure the  
> fact that there is a hidden symmetry in the problem:
>
> maxsubarrays xs = pickBest  (return xs >>= inits >>= tails)
>  where pickBest = maximumBy (compare `on` sum)
>   -- NOTE: Since pickBest is invariant under permutation of its arg,
>   --       the order of inits and tails above may be reversed.
>
> Dan Weston

Nice. Here's a pointless version:

maxsubarrays = maximumBy (compare `on` sum) . (>>= tails) . inits

Though I avoided using the list monad in the first solution, since I  
thought it would make the code less understandable for a beginner.

/Björn


More information about the Haskell-Cafe mailing list