-- Haskell98!
-- Safe list functions
module NList (FullList,
fromFL,
indeedFL,
decon,
head,
tail,
Listable (..)
) where
import Prelude hiding (head, tail)
newtype FullList a = FullList [a] -- data constructor is not exported!
fromFL (FullList x) = x -- Injection into general lists
-- The following is an analogue of `maybe'
indeedFL :: [a] -> w -> (FullList a -> w) -> w
indeedFL x on_empty on_full
| null x = on_empty
| otherwise = on_full $ FullList x
-- A possible alternative, with an extra Maybe tagging
-- indeedFL :: [a] -> Maybe (FullList a)
-- A more direct analogue of `maybe', for lists
decon :: [a] -> w -> (a -> [a] -> w) -> w
decon [] on_empty on_full = on_empty
decon (h:t) on_empty on_full = on_full h t
-- The following are _total_ functions
-- They are guaranteed to be safe, and so we could have used
-- unsafeHead# and unsafeTail# if GHC provides though...
head :: FullList a -> a
head (FullList (x:_)) = x
tail :: FullList a -> [a]
tail (FullList (_:x)) = x
-- Mapping over a non-empty list gives a non-empty list
instance Functor FullList where
fmap f (FullList x) = FullList $ map f x
-- Adding something to a general list surely gives a non-empty list
infixr 5 !:
class Listable l where
(!:) :: a -> l a -> FullList a
instance Listable [] where
(!:) h t = FullList (h:t)
instance Listable FullList where
(!:) h (FullList t) = FullList (h:t)