Can one express catamorphism through Data.Function.fix?

吃可爱长大的小学妹 提交于 2020-02-04 05:33:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/48705438/can-one-express-catamorphism-through-data-function-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!