Skip to content

Add safe function to convert partial functions on empty lists to total functions? #69

Closed
@Gabriella439

Description

@Gabriella439

The idea is to add this function to Data.List:

safe :: ([a] -> b) -> [a] -> Maybe b
safe f [] = Nothing
safe f xs = Just (f xs)

… which you can use like this:

safe head :: [a] -> Maybe a

safe last :: [a] -> Maybe a

safe tail :: [a] -> Maybe [a]

safe maximum :: Ord a => [a] -> Maybe a

… and so on. Another possible variation on this proposal is to define safe to work on Foldables instead of monomorphic lists:

safe :: Foldable f => (f a -> b) -> f a -> Maybe b
safe f xs
    | null xs   = Nothing
    | otherwise = Just (f xs)

… in which case it would probably go in Data.Foldable instead of Data.List.

Metadata

Metadata

Assignees

No one assigned

    Labels

    withdrawnWithdrawn by proposer

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions