Could this function be done as a list comprehension or fold? I suppose the "bail early" clauses at the bottom are helpful, but it could also be done with throws I suppose.