Project Inquiry

Implement Prelude.sum

Challenge
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude hiding (sum)

main :: IO ()
main = putStrLn $ if test then "SUCCESS" else "FAILURE"

test :: Bool
test = foldl (&&) True [ sum [] == 0
                       , sum [0.5] == 0.5
                       , sum [1, 2] == 3
                       , sum [1, 2, 3] == 6
                       , sum [1.0, 1.5, 2.0, 2.5] == 7.0
                       ]

-- TODO
sum :: (Num a) => [a] -> a
sum = undefined
Solution
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude hiding (sum)

main :: IO ()
main = putStrLn $ if test then "SUCCESS" else "FAILURE"

test :: Bool
test = foldl (&&) True [ sum [] == 0
                       , sum [0.5] == 0.5
                       , sum [1, 2] == 3
                       , sum [1, 2, 3] == 6
                       , sum [1.0, 1.5, 2.0, 2.5] == 7.0
                       ]

-- DONE
sum :: (Num a) => [a] -> a
sum []     = 0
sum (x:xs) = x + sum xs