Skip to content

Instantly share code, notes, and snippets.

@marcmartino
Last active June 15, 2021 23:18
Show Gist options
  • Save marcmartino/aa899752a6d306547370beb30211a060 to your computer and use it in GitHub Desktop.
Save marcmartino/aa899752a6d306547370beb30211a060 to your computer and use it in GitHub Desktop.
Less Contrived Pattern Match

Less Contrived Pattern Matching Example

Working my way through beginner elm exercises I needed to write a function to remove leading zeros from a list and it turned out to be a great illustration of how nice pattern matching can be.

in js the solution would be something like

const removeLeadingZeros = (xs) => 
          xs[0] === 0 
              ? removeLeadingZeros(xs.slice(1)) 
              : xs

or in python

def removeLeadingZeros(xs):
  return  removeLeadingZeros(xs[1:]) if xs[0] == 0 else xs

in elm it can be expressed this way

removeLeadingZeros : List Int -> List Int
removeLeadingZeros list =
    case list of
        0 :: xs ->
            removeLeadingZeros xs

        _ ->
            list

Surely one is not "better" than the other- but I think this well demonstrates some pros and cons. The js version is very succinct while the elm version is very declarative.

@marcmartino
Copy link
Author

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