# Haskell Quiz/Maximum Sub-Array/Solution Ninju

### From HaskellWiki

< Haskell Quiz | Maximum Sub-Array(Difference between revisions)

(2 intermediate revisions by one user not shown) | |||

Line 1: | Line 1: | ||

+ | [[Category:Haskell Quiz solutions|Maximum Sub-Array]] |
||

+ | |||

No clever stuff here unfortunately. |
No clever stuff here unfortunately. |
||

Line 12: | Line 14: | ||

let maxSubArray = maximumSubArray array |
let maxSubArray = maximumSubArray array |
||

putStrLn $ "The maximum sub array in " ++ show array ++ " is " ++ show maxSubArray |
putStrLn $ "The maximum sub array in " ++ show array ++ " is " ++ show maxSubArray |
||

− | return () |
||

maximumSubArray :: [Integer] -> [Integer] |
maximumSubArray :: [Integer] -> [Integer] |
||

Line 20: | Line 21: | ||

-- e.g. slices [1,2,3] = [[1], [1,2], [1,2,3], [2], [2,3], [3]] |
-- e.g. slices [1,2,3] = [[1], [1,2], [1,2,3], [2], [2,3], [3]] |
||

slices :: Eq a => [a] -> [[a]] |
slices :: Eq a => [a] -> [[a]] |
||

− | slices [] = [[]] |
+ | slices [] = [] |

− | slices xs = filter (not . (== [])) $ inits xs ++ slices (tail xs) |
+ | slices xs = tail $ inits xs ++ slices (tail xs) |

</haskell> |
</haskell> |

## Latest revision as of 02:28, 22 August 2008

No clever stuff here unfortunately.

module Main where import System.Environment import Data.List import Data.Ord main :: IO () main = do args <- getArgs let array = map read args let maxSubArray = maximumSubArray array putStrLn $ "The maximum sub array in " ++ show array ++ " is " ++ show maxSubArray maximumSubArray :: [Integer] -> [Integer] maximumSubArray = last . sortBy (comparing sum) . slices -- returns all sub lists of a given list not including the empty list -- e.g. slices [1,2,3] = [[1], [1,2], [1,2,3], [2], [2,3], [3]] slices :: Eq a => [a] -> [[a]] slices [] = [] slices xs = tail $ inits xs ++ slices (tail xs)