Skip to content

Potentially more efficient fromMap operation. #136

@jonathanknowles

Description

@jonathanknowles

The fromMap operation is currently defined as:

fromMap :: MonoidNull v => Map k v -> MonoidMap k v
fromMap = MonoidMap . Map.mapMaybe maybeNonNull

Internally, this always creates a new Map structure, even if the original Map is already in canonical form (i.e., contains no mempty values).

It might be desirable to first check whether the provided Map is in canonical form, and if so, just perform a coercion, thus avoiding the creation of a new Map structure:

fromMap :: MonoidNull v => Map k v -> MonoidMap k v
fromMap m
    | not (any MonoidNull.null m) = coerce m
    | otherwise = MonoidMap (Map.mapMaybe maybeNonNull m)

However, one downside of this optimisation is that it penalises the general case, which would now require two traversals of the original map, whereas before only one traversal was required.

We might be able to get the best of both worlds by providing two operations, and allowing the caller to choose:

fromMap :: MonoidNull v => Map k v -> MonoidMap k v
fromMap = MonoidMap . Map.mapMaybe maybeNonNull

fromMapNonNull :: MonoidNull v => Map k v -> MonoidMap k v
fromMapNonNull m
    | not (any MonoidNull.null m) = coerce m
    | otherwise = fromMap m

Metadata

Metadata

Assignees

No one assigned

    Labels

    ideaIdea for improvement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions