“Any function on finite lists that is defined by pairing the desired result with the argument list can always be redefined in terms of fold”

旧城冷巷雨未停 提交于 2019-12-04 02:13:30

Given the remark that you can / may need to use the original function inside, the claim as stated in your question seems trivial to me:

rewriteAsFold :: ([a] -> (b, [a])) -> [a] -> (b, [a])
rewriteAsFold g = foldr f v where
    f x ~(ys,xs) = (fst (g (x:xs)), x:xs)
    v            = (fst (g []), [])

EDIT: Added the ~, after which it seems to work for infinite lists as well.

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