Skip to content

Instantly share code, notes, and snippets.

@evancz
Last active February 22, 2016 04:59
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 evancz/e590750a5bd1ea04c2d2 to your computer and use it in GitHub Desktop.
Save evancz/e590750a5bd1ea04c2d2 to your computer and use it in GitHub Desktop.

Here is one of the changes I needed to make in package.elm-lang.org.

The issue was that the code was relying on linkQualified to always get a non-empty string as the token argument. While it is true that that will happen for the foreseeable future, I took this as an opportunity to do a more serious refactor so that the code was nicer and if it ever breaks in the future it will give me a very specific message.

Before

linkQualified : List String -> String -> Text.Text
linkQualified modules token =
  case List.reverse (String.split "." token) of
    name :: rest ->
      let
        qualifiers = List.reverse rest
      in
        if List.member (String.join "." qualifiers) modules
        then
          Text.link
            (String.join "-" qualifiers ++ "#" ++ name)
            (Text.fromString name)
        else
          Text.fromString name

After

linkQualified : List String -> String -> Text.Text
linkQualified modules token =
    let
        (qualifiers, name) =
            splitLast (String.split "." token)
    in
        if List.member (String.join "." qualifiers) modules then
            Text.link (String.join "-" qualifiers ++ "#" ++ name) (Text.fromString name)

        else
            Text.fromString name


splitLast : List a -> (List a, a)
splitLast list =
    case list of
        [] ->
            Debug.crash "cannot call splitLast on an empty list"

        [x] ->
            (x, [])

        x :: rest ->
            let
                (xs, last) = splitLast rest
            in
                (x :: xs, last)
@raiscui
Copy link

raiscui commented Feb 22, 2016

oh,
[x] -> (x, [])

shoud be:
[x] -> ([], x)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment