Project Inquiry

List head and last

Challenge
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude hiding (head, last)

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

test :: Bool
test = and [ head ([] :: [Int]) == Nothing
           , last ([] :: [Int]) == Nothing
           , head [1..3] == Just 1
           , last [1..3] == Just 3
           ]

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

module Main where

import           Prelude hiding (head, last)

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

test :: Bool
test = and [ head ([] :: [Int]) == Nothing
           , last ([] :: [Int]) == Nothing
           , head [1..3] == Just 1
           , last [1..3] == Just 3
           ]

-- DONE
head :: [a] -> Maybe a
head []    = Nothing
head (x:_) = Just x

last :: [a] -> Maybe a
last = head . reverse