As a minor optimization you can avoid computing the O(n) length of the list here again (pass the length in the case statement above).