Project Inquiry

Implement Functor instance 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 [ fmap ((*) 2) CNil == CNil
           , fmap ((*) 2) (CCons 1 CNil) == CCons 2 CNil
           , fmap ((*) 2) (CCons 1 (CCons 2 CNil)) == CCons 2 (CCons 4 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 [ fmap ((*) 2) CNil == CNil
           , fmap ((*) 2) (CCons 1 CNil) == CCons 2 CNil
           , fmap ((*) 2) (CCons 1 (CCons 2 CNil)) == CCons 2 (CCons 4 CNil)
           ]

-- DONE
instance Functor C where
  -- fmap :: (a -> b) -> C a -> C b
  fmap _ CNil         = CNil
  fmap f (CCons x xs) = CCons (f x) (fmap f xs)