How does foldr work?

The easiest way to understand foldr is to rewrite the list you’re folding over without the sugar. [1,2,3,4,5] => 1:(2:(3:(4:(5:[])))) now what foldr f x does is that it replaces each : with f in infix form and [] with x and evaluates the result. For example: sum [1,2,3] = foldr (+) 0 [1,2,3] [1,2,3] … Read more

Y combinator discussion in “The Little Schemer”

Great question. For the benefit of those without a functioning DrRacket installation (myself included) I’ll try to answer it. First, let’s use some sane (short) variable names, easily trackable by a human eye/mind: ((lambda (h) ; A. (h h)) ; apply h to h (lambda (g) (lambda (lst) (if (null? lst) 0 (add1 ((g g) … Read more

foldl is tail recursive, so how come foldr runs faster than foldl?

Welcome to the world of lazy evaluation. When you think about it in terms of strict evaluation, foldl looks “good” and foldr looks “bad” because foldl is tail recursive, but foldr would have to build a tower in the stack so it can process the last item first. However, lazy evaluation turns the tables. Take, … Read more

What is a Y-combinator? [closed]

A Y-combinator is a “functional” (a function that operates on other functions) that enables recursion, when you can’t refer to the function from within itself. In computer-science theory, it generalizes recursion, abstracting its implementation, and thereby separating it from the actual work of the function in question. The benefit of not needing a compile-time name … Read more