Project Inquiry

Implement reverse 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 [ reverse (CNil :: C Integer) == CNil
           , reverse (CCons 1 CNil) == CCons 1 CNil
           , reverse (CCons 1 (CCons 2 CNil)) == CCons 2 (CCons 1 CNil)
           ]

-- 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 [ reverse (CNil :: C Integer) == CNil
           , reverse (CCons 1 CNil) == CCons 1 CNil
           , reverse (CCons 1 (CCons 2 CNil)) == CCons 2 (CCons 1 CNil)
           ]

-- DONE
reverse :: C a -> C a
reverse CNil         = CNil
reverse (CCons x xs) = append x (reverse xs)
  where append :: a -> C a -> C a
        append a CNil         = CCons a CNil
        append a (CCons x xs) = CCons x (append a xs)