this can potentially be implemented easier with some notion of partial functions and better constructor based pattern match. Alternatively you can implement this with a
tailrec
function that loops over the list accumulating manually which is essentially what