Skip to content

New extra combinator: generalised 'readMaybe' #161

@josephcsible

Description

@josephcsible

readMaybe is implemented like this:

readMaybe :: Read a => String -> Maybe a
readMaybe s = case readEither s of
                Left _  -> Nothing
                Right a -> Just a

There's a lot of other types that it would be useful to generalize this to. Here's two ideas I've had:

readFail :: (MonadFail f, Read a) => String -> f a
readFail s = case readEither s of
                Left e  -> fail e
                Right a -> return a
readAlt :: (Alternative f, Read a) => String -> f a
readAlt s = case readEither s of
                Left _  -> empty
                Right a -> pure a

Both of those are the same as readMaybe when f ~ Maybe. The first is useful for custom error monads to preserve whether the problem was "no parse" or "ambiguous parse". The second is useful for MaybeT and lots of other things that have some sort of failure state.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestnewBring something new into library (add function or type or interface)questionFurther information is requestedreexportReexport something new

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions