Thomas Hartman thomas.hartman at db.com
Tue Jul 17 18:53:47 EDT 2007

```hartthoma at linuxpt:~/ProjectRepos/learning\$ ghc -fglasgow-exts -e 'main'
maxSubArrays.hs
should be [2,5,-1,3]:
[2,5,-1,3]
hartthoma at linuxpt:~/ProjectRepos/learning\$ cat maxSubArrays.hs
import Data.List
-- maximum sub-array:  [2, 5, -1, 3]
main = do putStrLn \$ "should be " ++ show [2, 5, -1, 3] ++ ":"
putStrLn \$ show \$ maxsubarray [-1, 2, 5, -1, 3, -2, 1]

maxsubarray :: forall a. (Ord [a], Ord a, Num a) => [a] -> [a]
maxsubarray a = head \$ reverse \$ sortBy comparelists \$ sublists a

comparelists l1 l2 = compare (sum l1) (sum l2)
sublists a = nub \$ sort \$ concat \$ map inits \$ tails a
hartthoma at linuxpt:~/ProjectRepos/learning\$

cheers :)

t.

James Hunt <james at j-hunt.co.uk>
07/17/2007 04:26 PM

To
cc

Subject

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]

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
_______________________________________________

---

This e-mail may contain confidential and/or privileged information. If you
are not the intended recipient (or have received this e-mail in error)
please notify the sender immediately and destroy this e-mail. Any
unauthorized copying, disclosure or distribution of the material in this
e-mail is strictly forbidden.
-------------- next part --------------
An HTML attachment was scrubbed...