2

I have this lovely fixana function here that performs about 5 times faster than her sister ana. (i have a criterion report to back me on this)

ana alg = Fix . fmap (ana alg) . alg

fixana alg = fix $ \f -> Fix . fmap f . alg

Can I express their cousin cata in the same fashion?

cata f = f . fmap (cata f) . unFix

It seems to me that I cannot, but I have been humbled by my S.O. fellows quite a few times in the past.

duplode
  • 31,361
  • 7
  • 69
  • 130
Ignat Insarov
  • 4,444
  • 13
  • 34
  • 2
    I don't understand. What happens if you try the analogous `fixcata f = fix $ \g -> f . fmap g . unFix` ? – chi Feb 09 '18 at 12:22
  • @chi Oh. Defeated again. I'm poor with fixpoints. I should probably delete this question to avoid embarrassment. – Ignat Insarov Feb 09 '18 at 12:36
  • 4
    SO is not a game when one gets "defeated" :) There's nothing wrong in asking a question without knowing the answer beforehand -- indeed that's the whole point of asking! – chi Feb 09 '18 at 12:48

1 Answers1

4

Actually, this has nothing to do with catamorphisms.

Whenever a function is defined as

f = (... f ...)   -- some expression involving f

one can rewrite it using fix as

f = fix $ \g -> (... g ...)

In the posted code we have a slight variant

f x = (... (f x) ...)

We can regard the above as f being defined recursively. However, it's simpler if we regard f x (rather than f) being defined recursively.

f x = fix $ \g -> (... g ...)

This should be more efficient than the plain translation

f = fix $ \g x -> (... (g x) ...)

since we don't need to call g over and over again with the same argument x.

chi
  • 101,733
  • 3
  • 114
  • 189
  • Thank you! Can you also take a look at the updated post? – Ignat Insarov Feb 09 '18 at 13:17
  • 2
    @Kindaro you should make that update (which I rolled back for now) a separate question, since it doesn't directly relate to the original question's title. – leftaroundabout Feb 09 '18 at 13:27
  • 1
    @Kindaro Also see [this](https://stackoverflow.com/questions/12999385/why-does-ghc-make-fix-so-confounding) first. I think it's exactly the same issue which improves performance. – chi Feb 09 '18 at 14:00