Project Inquiry

Implement reduce function for custom collection type

Challenge
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude hiding (reverse)

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

data C a = CCons a (C a) | CNil deriving (Eq)

test :: Bool
test = and [ reduce (+) 0 CNil == 0
           , reduce (+) 1 (CCons 1 CNil) == 2
           , reduce (+) 2 (CCons 1 (CCons 2 CNil)) == 5
           ]

-- TODO: This program doesn't compile. Define the missing function(s) incl. type signatures!
Solution
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude hiding (reverse)

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

data C a = CCons a (C a) | CNil deriving (Eq)

test :: Bool
test = and [ reduce (+) 0 CNil == 0
           , reduce (+) 1 (CCons 1 CNil) == 2
           , reduce (+) 2 (CCons 1 (CCons 2 CNil)) == 5
           ]

-- DONE
reduce :: (a -> a -> a) -> a -> C a -> a
reduce f start (CNil)       = start 
reduce f start (CCons x xs) = reduce f (f start x) xs