Bjorn Bringert bringert at cs.chalmers.se
Tue Jul 17 17:08:34 EDT 2007

```On Jul 17, 2007, at 22:26 , James Hunt wrote:

> Hi,
>
> As a struggling newbie, I've started to try various exercises in
> order to improve. I decided to try the latest Ruby Quiz (http://
> www.rubyquiz.com/quiz131.html) in Haskell. Would someone be kind
> enough to cast their eye over my code? I get the feeling there's a
> better way of doing it!
>
> subarrays :: [a] -> [[a]]
> subarrays [] = [[]]
> subarrays xs = (sa xs) ++ subarrays (tail xs)
>  where sa xs = [ys | n <- [1..length xs], ys <- [(take n xs)]]
>
> maxsubarrays :: [Integer] -> [Integer]
> maxsubarrays xs = msa [] (subarrays xs)
>  where
>    msa m [] = m
>    msa m (x:xs)
>      | sum x > sum m = msa x xs
>      | otherwise     = msa m xs
>
> --for testing: should return [2, 5, -1, 3]
> main = maxsubarrays [-1, 2, 5, -1, 3, -2, 1]
>
> to find any that teach you how to really "think" in a Haskell way.
> Is there anything (books, online tutorials, exercises) that anyone
> could recommend?
>
> Thanks,
> James

Hi james,

here's one solution:

import Data.List

maxsubarrays xs = maximumBy (\x y -> sum x `compare` sum y) [zs | ys
<- inits xs, zs <- tails ys]

This can be made somewhat nicer with 'on':

import Data.List

maxsubarrays xs = maximumBy (compare `on` sum) [zs | ys <- inits xs,
zs <- tails ys]

on, which will appear in Data.Function in the next release of base,
is defined thusly:

on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(*) `on` f = \x y -> f x * f y

/Björn

```