-- |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
  [] -> Maybe a
forall a. Maybe a
Nothing
  a
a : [a]
_ -> a -> Maybe 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
  [] -> Maybe a
forall a. Maybe a
Nothing
  [a]
as -> a -> Maybe a
forall a. a -> Maybe a
Just ([a] -> a
forall a. HasCallStack => [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
  [] -> Maybe [a]
forall a. Maybe a
Nothing
  [a]
as -> [a] -> Maybe [a]
forall a. a -> Maybe a
Just ([a] -> [a]
forall a. HasCallStack => [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
  [] -> Maybe [a]
forall a. Maybe a
Nothing
  [a]
as -> [a] -> Maybe [a]
forall a. a -> Maybe a
Just ([a] -> [a]
forall a. HasCallStack => [a] -> [a]
List.tail [a]
as)
{-# inline tail #-}