Project Inquiry

Implement length function for custom collection type

Challenge
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude hiding (length)

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

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

test :: Bool
test = and [ length CNil == 0
           , length (CCons 1 CNil) == 1
           , length (CCons 1 (CCons 2 CNil)) == 2
           ]

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

module Main where

import           Prelude hiding (length)

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

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

test :: Bool
test = and [ length CNil == 0
           , length (CCons 1 CNil) == 1
           , length (CCons 1 (CCons 2 CNil)) == 2
           ]

-- DONE
length :: C a -> Int
length CNil        = 0
length (CCons _ c) = 1 + length c