“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”

前端 未结 1 2001
谎友^
谎友^ 2021-02-19 18:42

I was reading through the paper A tutorial on the universality and expressiveness of fold, and am stuck on the section about generating tuples. After showing of how the normal d

1条回答
  •  抹茶落季
    2021-02-19 19:07

    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.

    0 讨论(0)
提交回复
热议问题