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.
second example here: https://gist.github.com/marcmartino/70cce4b5ab122c8fd8c10491d75f6991