module Hcompta.Lib.NonEmpty where import Data.Function ((.)) import qualified Data.List import Data.List.NonEmpty (NonEmpty(..)) import Data.Maybe (Maybe(..)) import Data.Monoid (Monoid(..)) -- | Return the given 'NonEmpty' without its last section if any. parent :: NonEmpty x -> Maybe (NonEmpty x) parent (_:|[]) = Nothing parent (x:|xs) = Just (x:|Data.List.init xs) -- | Return all the ancestors (i.e. prefixes) -- of the given 'NonEmpty' (including itself). ancestors_or_self :: NonEmpty x -> [NonEmpty x] ancestors_or_self (y:|ys) = go y [] ys [] where go :: x -> [x] -> [x] -> [NonEmpty x] -> [NonEmpty x] go x0 s [] = (:) (x0:|s) go x0 s (x:xs) = go x0 (s `mappend` [x]) xs . (:) (x0:|s)