Reverse String

Authors

Publication

Pub Details

Date

Pages

See all articles from QL Hacker's Journal 20

In one of the programming newsgroups I read, I saw a couple of postings dealing with how to reverse a string or a list. A short example would be to take the string “abcde” and make it “edcba”.This little puzzle seemed interesting, so I thought I would give it a shot myself.

My first approach is purely interactive. Find the length of the string and then do a FOR loop backwards through the string, adding each character to another string.

   DEFine FuNction reverse$ (in$)
LOCal rev$, length
rev$=""
length = LEN(in$)
FOR x = length TO 1 STEP -1
rev$ = in$(x)
NEXt x
RETURN rev$
END DEFine

The examples I saw were recursive based, so I thought I would try that approach.

   DEFine FuNction reverse$ (in$)
LOCal temp$
if LEN(in$)=1 THEN RETURN in$
temp$ = reverse$( in$( 2 TO )
RETURN temp$ & in$(1)
END DEFine

How I wrote this reminded me of how I used to do a few Lisp programs. You have to start the procedure with the end condition first. You have to think about how you want the recursion to stop and check for this condition at the start. I then decided to try this program in Lisp using the WS-Lisp interpreter. My first attempt was very similar to the example below. When I was looking at the example code that came with WS-Lisp, I found that it had a reverse function in that example code. I saw that my code was going in the same direction as the example code, but my syntax was lacking. Below is the example code.

   (de reverse (rev_list)
(cond
( (isatom rev_list) rev_list )
( t (append (reverse (cdr rev_list)) (list (car rev_list))))
) ; end of cond
) ; end of de reverse

Then upon further looking, there was another version of a reverse program that also came with WS-Lisp. It’s a bit longer than the first version and not quite as easy to read (at least for me). It seems to rely on the simplest Lisp words. I don’t know if it was written to use the lowest level Lisp words or not. Anyway, it’s another example to ponder.

(de rev (liste)
(cond
( (isnull liste) liste )
( (isnull (cdr liste)) liste )
( t
(cons
(car (rev (cdr liste)))
(rev
(cons
(car liste)
(rev (cdr (rev (cdr liste))))
)
)
)
) ; end of t
) ; end of cond
) ; end of de

I’m sure my SuperBasic programs are not the most elegant and can be improved upon. As they said in college, “I leave it as an exercise to the reader.”

Products

 

Downloadable Media

 

Image Gallery

Scroll to Top