I’m going through The LIttle Schemer to learn Scheme (as an old C programmer) and as an exercise I tried to write a procedure to flatten a list using only the forms in The Little Schemer; I.e., define, lambda, cond, car, cdr, and, or, etc., but not append. I thought it would be easy but I haven’t been able to come up with a solution. How can I do this ?
I’m going through The LIttle Schemer to learn Scheme (as an old C programmer)
Share
I have a version that uses only “first-principles” operations and is efficient (does not require more than one pass through any of the lists, unlike
append-based solutions). 🙂It does this by defining two simple building blocks (
foldandreverse), and then definingflatten(and its helper,reverse-flatten-into) atop those (and notice how each function is just one or two lines long):The only external functions used are:
cons,car,cdr,null?, andpair?.The key insight from this function is that
foldis a very powerful operation, and should be part of any Schemer’s toolkit. And, as seen in the code above, it’s so simple to build from first principles!