Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!snorkelwacker.mit.edu!apple!sun-barr!cs.utexas.edu!samsung!emory!gatech!udel!princeton!fourier!markv From: markv@fourier.Princeton.EDU (Mark VandeWettering) Newsgroups: comp.lang.scheme Subject: Re: Scheme recursive procedures Message-ID: <5834@idunno.Princeton.EDU> Date: 31 Jan 91 15:57:05 GMT References: <11739@darkstar.ucsc.edu> Sender: news@idunno.Princeton.EDU Reply-To: markv@fourier.Princeton.EDU (Mark VandeWettering) Organization: Princeton University Lines: 36 In article <11739@darkstar.ucsc.edu> gforce@ucscb.UCSC.EDU (60766000) writes: > >Can one of you scheme hackers out there help me with a prog. problem ? >the version of scheme at my school doesn't have the function "reverse" >I am trying to write one but so far have only come up with one that is >recursive but needs to take in two arguments.. CAn someone show me a way >to do it with only one ?.. > >Thanx Sigh! Someone should work harder to understand what is going on. If you can't code reverse, then you can't code LOTS. But, in true spirit of a spoiler.... Try any one of the following (done off the top of my head): (define (reverse l) (if (null? l) '() (append (reverse (cdr l)) (car l)))) This is ugly because of the append. Appending does lots and lots of consing. It is also not tail recursive, so it consumes stack. First, let's deal with the tail recursion problem.... (define (reverse-tr l) (define (rloop l r) (if (null? l) r (rloop (cdr l) (cons (car l) r)))) (rloop l '())) By some strange coincidence, we also have gotten rid of the append problem. This will execute in all reasonable Scheme implementations with a constant amount of stack, since it is fully tail recursive. Mark VandeWettering markv@acm.princeton.edu