Refactor Folds Tool?

I reach for folds a lot.

After hearing Don Syme talk about code he would rather avoid, he mentioned folds, and how they “are the goto of functional programming”.

Mine can sometimes get overly complicated…

Is there a tool in Haskell which could automatically give a few suggestions on how to factor away from powerful folds to simpler functions?

I imagine it’d be useful for me while programming in other languages also - but Haskell seems like the natural place to find such a tool - purity, using type definitions to search for replacements…

I was actually working on something along these lines not too long ago! The idea was to have a source plugin that provided an additional warning about recursive code. It wouldn’t suggest how to refactor it, I think that’s a much harder problem. I wanted this mostly as I was learning the recursion-schemes library and I learn better in a familiar context - so I thought “why not refactor some work code?”. That’s a nice idea, but work code spans some 500+ modules and there’s no way I’m going to trawl through that looking for something that can be replaced with cata!

That’s the good news. The bad news is I didn’t really get far. I can try and dig the code out and throw it on GitHub though.

1 Like

I never looked into the recursion scheme lib - looks v nice!

Somehow I thought limiting the refactor to primitive recursion / folds would make it doable… but perhaps not!

I think hlint (http://hackage.haskell.org/package/hlint) has some hints that include standard fold transforms – nothing too fancy or general, but it does hit a lot of common cases through pure pattern matching.

1 Like

For my Msc. Thesis, I worked on something related – a GHC plugin to transform explicitly recursive functions to folds, so they can benefit from build/foldr fusion.

The implementation is horribly slow but I still think it’s an interesting idea, in some cases explicit recursion is still easier to read/write.

2 Likes

I suspected this, need to give hlint another look