Yay, I wrote my first recursive function in Elm today.
I was working on the 99 problems tutorial and it had this question:
How do you find the last element in a list?
I know that in Ruby, we can use the .last method to get it, but in Elm, there’s no such method.
So I tried this:
lastElement xs = case xs of
 -> Nothing
[x] -> Just x
y::ys -> lastElement ys
And it worked! Yay! So to explain the code, lastElement is the function that takes a list xs as its argument. The resulting cases are:
- If the list is empty ([ ]), it returns Nothing,
- If there’s one element in the list ([x]), it returns it (x).
- If the list contains more than one element (y::ys), we will ignore the first element (y) and call the same function lastElement recursively on the rest of the list (ys). Thus, we will keep eliminating the head of the list until we reach the last element and return it.
This works as tested here.
I’m happy because I’m starting to see some results in my quest to learn Elm. 🙂