-- |Variants of the uncons and unsnoc combinators for lists that return 'Maybe'.
module Incipit.List where

import qualified Data.List as List
import Data.Maybe (Maybe (..))

-- |Return 'Just' the head of a list.
head :: [a] -> Maybe a
head :: forall a. [a] -> Maybe a
head = \case
  [] -> forall a. Maybe a
Nothing
  a
a : [a]
_ -> forall a. a -> Maybe a
Just a
a
{-# inline head #-}

-- |Return 'Just' the last element of a list.
last :: [a] -> Maybe a
last :: forall a. [a] -> Maybe a
last = \case
  [] -> forall a. Maybe a
Nothing
  [a]
as -> forall a. a -> Maybe a
Just (forall a. [a] -> a
List.last [a]
as)
{-# inline last #-}

-- |Return 'Just' the non-last elements of a list.
init :: [a] -> Maybe [a]
init :: forall a. [a] -> Maybe [a]
init = \case
  [] -> forall a. Maybe a
Nothing
  [a]
as -> forall a. a -> Maybe a
Just (forall a. [a] -> [a]
List.init [a]
as)
{-# inline init #-}

-- |Return 'Just' the non-head elements of a list.
tail :: [a] -> Maybe [a]
tail :: forall a. [a] -> Maybe [a]
tail = \case
  [] -> forall a. Maybe a
Nothing
  [a]
as -> forall a. a -> Maybe a
Just (forall a. [a] -> [a]
List.tail [a]
as)
{-# inline tail #-}