Skip to content

Instantly share code, notes, and snippets.

@lenards
Forked from JoelQ/elm-maybe-map-compose.md
Created July 23, 2022 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lenards/13ed1222e9913c8f089ee6a6f3d3874c to your computer and use it in GitHub Desktop.
Save lenards/13ed1222e9913c8f089ee6a6f3d3874c to your computer and use it in GitHub Desktop.
Refactoring a pipeline of Maybe.map functions in Elm

Refactoring maybe code in Elm

Given this ugly series of cases:

optionalFormattedFriendAddress : Maybe Friend -> Maybe String
optionalFormattedFriendAddress maybeFriend =
  let
    maybeAddress = case maybeFriend of
      Just friend -> Just friend.address
      Nothing -> Nothing

    maybeLine1 = case maybeAddress of
      Just address -> Just address.line1
      Nothing -> Nothing

  in
    case maybeLine1 of
      Just line1 -> Just (String.toUpper line1)
      Nothing -> Nothing

I can refactor to a pipeline of maps:

maybeFriend
  |> Maybe.map .address
  |> Maybe.map .line1
  |> Maybe.map String.toUpper

Map functions compose so it can be flattened to:

maybeFriend
  |> Maybe.map (String.toUpper << .line1 << .adddress)

This can finally be extracted to a function:

formattedAddress : Friend -> String
formattedAddress friend =
  String.toUpper friend.address.line1
  
optionalFormattedFriendAddress : Maybe Friend -> Maybe String
optionalFormattedFriendAddress maybeFriend =
  Maybe.map formattedAddress maybeFriend
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment