Factor out foldable better to reduce code duplication. 

Factor out foldable better to reduce code duplication. 

r? @pcwalton (probably want to let travis run...)