The other day @natefaubion mentioned an idea that popped into his head for an approach to using normal folds to create short circuiting folds. I though it was really interesting so I decided to go ahead and try to implement it. Here is the result
Return introduces a new data type
data Return a = Cont a | Return a
and a function
mkReturnable :: ∀ a. ((Return a -> a) -> a) -> a
mkReturnable you can create functions that “return” values early in a way that you normally would have to use explicit recursion to accomplish.
foldl' :: ∀ a b f. Foldable f => (b -> a -> Return b) -> b -> f a -> b foldl' f init as = mkReturnable \return -> foldl (\b a -> return $ f b a) init as
This is nice because it allows for you to define, for fee, folds that can exit early for anything that already has a
Foldable instance, instead of having to use recursion to handle each differently.
However, I don’t know what to think of this. On one hand, the API to create short circuiting functions just feels a little off to me. I think it’s because you’re using the FFI to make an abstraction that can’t be made within PS itself (afaict). But on the other hand, I think it’s type safe and I would guess that any function you can create with this could also be created without it. It also allows for potentially more performant code without doing an entire implementation via the FFI.
So, can you think of any way this can be misused? Is there a better way to accomplish this? Is this something worth accomplishing? What are your thoughts?
- I don’t care