Not sure about whether the types are going to work out, but maybe the `if(...) else foldLeft` can be replaced with `reduce`?