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 ?
相关问题
- Generating powerset in one function, no explicit r
- What is fixed point?
- unfold function in scheme
- returns the first n of list
- How to use (read) correctly in mit-scheme?
相关文章
- Does learning one Lisp help in learning the other?
- What is the definition of “natural recursion”?
- How do I define a sub environment in scheme?
- Why is it legal in a function definition to make s
- How to split list into evenly sized chunks in Rack
- Difference between OOP and Functional Programming
- Good simple algorithm for generating necklaces in
- Why is there no tail recursion optimization in Ema
I'm not familiar with the Little Schemer primitives, so you may need to flavor this to suit.
I'm not sure if this is the answer you want, but you can write
append
using primitives:The
flatten
function could then be written in terms of this.Not sure if this is outside the rules or not :)
Here's an attempt. It gets away with using cons and avoiding append, because it only chips away the first non-pair it can get to and conses that to the flatten of a new tail it has built. Sometimes it rewrites the list then just calls flatten again. Def not the most efficient way.
Fixed code:
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 (
fold
andreverse
), 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
fold
is 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!