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

Good explanation of “Combinators” (For non mathematicians)

Unless you’re deeply into theory, you can regard the Y combinator as a neat trick with functions, like monads. Monads allow you to chain actions, the Y combinator allows you to define self-recursive functions. Python has built-in support for self-recursive functions, so you can define them without Y: > def fun(): > print “bla” > … 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

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