TweetFollow Us on Twitter

Iteration
Volume Number:1
Issue Number:10
Column Tag:Lisp Listener

"Iteration Techniques in Lisp"

By Andy Cohen, Human Factors Engineer, Hughes Aircraft, MacTutor Contributing Editor

Last month I showed how ExperLisp uses some of the simpler Quickdraw routines. For the curious, the following table contains all the Quickdraw routines discussed in the ExperLisp Reference Guide.

Quickdraw Routines

CLOSEPOLY CLOSERGN COPYRGN DIFFRGN DISPOSERGN DRAWCHAR DRAWSTRING EMPTYRGN EQUALRGN ERASEARC ERASEOVAL ERASEPOLY ERASERECT ERASERGN ERASEROUNDRECT FILLARC FILLOVAL FILLRECT FILLRGN FILLROUNDRECT FRAMEARC FRAMEOVAL FRAMEPOLY FRAMERECT FRAMERGN FRAMEROUNDRECT GETFONTINFO HIDECURSOR HIDEPEN INSETRGN INVERTARC INVERTOVAL INVERTPOLY INVERTRECT INVERTRGN INVERTROUNDRECT KILLPOLY LINE LINETO MOVE MOVETO NEWRGN OBSCURECURSOR OFFSETPOLY OFFSETRGN PAINTARC PAINTOVAL PAINTPOLY PAINTRECT PAINTRGN PAINTROUNDRECT PENMODE PENNORMAL PENPAT PENPOS PENSIZE SECTRGN SETEMPTYRGN SETRECTRGN SHOWCURSOR SHOWPEN SPACEEXTRA TEXTFACE T EXTFONT TEXTMODE TEXTSIZE UNIONRGN XORRGN

Quickdraw commands will be discussed in more detail as each command is used within the ExperLisp examples.

Iteration

Iteration is a process which provides a method of performing repetitive actions. In BASIC, iteration is accomplished with the FOR...NEXT or GOTO statements. Fortran uses the DO loop and Pascal REPEAT.....UNTIL. Experlisp has a number of different kinds of iteration, some of which look and act like those of the above.

The first kind of iteration requires use of the PROG special form. PROG stands for program and has a list of variables associated with it that are equal to nil when the PROG is evaluated. These variables are local and are bound to the PROG. The body of the PROG follows the variable list. The body contains forms or lists which are evaluated and consist of symbols, values or procedures. PROG by itself returns nil and it does not provide iteration. The special form GO within PROG is used with an arbitrary tag for iteration. The tag is placed where the loop begins within the PROG. GO tagname, placed further along within the PROG, puts the next evaluation to where the tag is. For example;

(defun iter () ;1
   (prog ((y 1)) ;2
     loop ;3
       (setq y (add1 y))  ;4
       (print y) ;5
       (if (not(= 6 y)) (go loop)))) ;6

(iter)  

When the above is compiled...

;iter
;2
;3
;4
;5
;6
;nil

The semicolon on each line of the sample is the method one uses for placing remarks within ExperLisp source code. Everything after the semicolon is ignored. The above PROG is within a defined procedure (iter). This makes it possible for the code to be compiled and then called as a procedure. Multiple PROGs are allowed within a DEFUN. However, the variables are local to each of the PROGs. It is wise to keep the number of PROGS within a defined procedure down to a minimum. The smaller the procedures, the easier to debug. Line 2 starts the PROG, declares the variable "y" and gives "y" the value of 1. ExperLisp syntax requires the variable or variables and their associated values be contained within an overall variable list. That is why the list "(y 1)" is contained within parentheses. Line 3 is the GO tag. Note, that it is not within it's own list. However, it is within the overall PROG list. In line 4 the value of y has the number 1 added to it. The value of this sum is then assigned to the symbol "y" using SETQ. Line 5 prints the value of "y" for each loop. Line 6 tests to see if the value of "y" equals ten. If it doesnt then the evaluation is sent to the GO tag, "loop". The entire process is then repeated until "(not(= 10 y))" returns "nil". If it does then the next evaluation takes place after line 6. Since Line 6 is actually the end of the PROG, nil is returned and the iteration is stopped. In order to get a value returned from a PROG one must use RETURN. RETURN not only returns a value, it also terminates the iteration. For example;

(defun iter (x)
 (prog ((y 1))
     loop
  (setq y (add1 y))
 (if(= x y) (RETURN "Y IS EQUAL TO X")
  (print y))
      (go loop)))

(iter 5)

In the above "x" is compared to "y". When found to be equal ExperLisp stops the iteration and returns the string as follows;

;Iter
;2
;3
;4
;Y IS EQUAL TO X

Early versions of Lisp use PROG and GO for iteration. Later versions, which strive to conform to the Common Lisp standard, are using a more efficient form of iteration form called DO. DO not only specifies the variable label, it can indicate an initial value, increment the value and contain a conditional for halting the iteration. The syntax for the DO special form is as follows:

(DO ((Variable   initial value 
        increment ) (Conditional))
       (form)
       (form)
       ....)

(Defun Iter2 (x)
   (DO ((y 1 (add1 y)))
       ((= y x) "Y IS EQUAL TO X")
      (Print y)))

The above is a DO version of the PROG sample, "Iter". It performs the same task however, it's output is slightly different.

; (iter2 5)
;1
;2
;3
;4
;"Y IS EQUAL TO X"

In the PROG version the addition of the number one to "y" is performed prior to the print command. Hence, the first number printed is two. In the DO version the ADD1 procedure is not performed until the second loop. The print "y" statement is performed in the first loop so that the number one is printed first. Note that when the conditional "(= y x)" is true the iteration is halted and what follows the conditional is returned. For another example, check out following:

(defun iterfun (x) ;1
   (do ((a 0 (add1 a))) ;2
       ((= a 5) 'done)  ;3
       (print (* a x))))  ;4

(iterfun 3)

;iterfun
;0 
;3 
;6 
;9 
;12 
;done

Line one of the above specifies the defined procedure and creates the symbol "x". In line two the variable "a" is initialized and assigned the value zero. On that same line the method of incrementation of the variable is also specified. Line three is the conditional and tests the variable "a" for equivalence with the number five. Line four prints the product of the value of "a" for each iteration and the value assigned to the symbol, "x". One of the features of DO is that one may use GOs and RETURNs just as in the PROG.

There is another form of DO for faster and simpler iteration. DOLIST assigns the elements of a list to a symbol. It then performs the functions within it's body upon each element of the list one at a time. It's syntax is as follows:

DOLIST (Symbol '(list)) (functions......)

(DOLIST (FUN '(Buy Mactutor Mag))
   (print fun)


;Buy
;Mactutor
;Mag
;nil

The print command is performed upon each member of the list assigned to "FUN". Note that it always returns nil when the iteration is complete. This is because the list assigned to "FUN" is exhausted. The list then contains nil.

One of the easiest to use forms of iteration (especially to someone who knows BASIC) is DOTIMES. Using DOTIMES one specifies only a variable which represents each loop and the maximum number of loops one wants performed. For example:

(Dotimes (turn 150)
   (forward (/ turn 2))
   (back (/ turn 2))
   (right turn))

When compiled or typed into the Listener Window the above list produces the following:

The symbol "turn" is initially zero. The body of DOTIMES is iterated 150 times. I used 150 so that enough lines would be drawn to make it interesting. Remember FORWARD? Well, BACK moves the pen backward. I divided "TURN" in half when the pen is moved so that the lines don't go off the column's margins. I'll continue with another form of iteration after the next couple of paragraphs.

Using the Mouse

Using the mouse as an input or interactive device with ExperLisp is quite simple. GETMOUSE reports the X-Y coordinates of the mouse's's pointer on the active window. Type the following in the Listener Window:

(GETMOUSE)
;(146  107 )

BUTTON is a predicate which returns "t" when it is evaluated and the mouse's button is held down. It returns nil when the button is not held down. The following is an example of GETMOUSE and BUTTON in iterative functions.

(defun Watch ()
   (prog ()
     look
     (if (button) (Mousey) 
     (go look))))


(defun Mousey ()
  (prog ()
   another
   (print (getmouse))
   (if (not(button)) 
    (halt) (go another))))



(defun halt ()
   (print"that's all folks!"))

(Watch)

The first of the three above procedures, Watch, waits for the mouse's button to be pressed. If it is not then the loop continues. When the button is pressed then Watch calls Mousey. Mousey will print the X-Y position of the mouse as long as the button is held down (remember, "(IF (then) (else))" ?). When the button is released Mousey calls Halt. Halt simply prints a message with no iteration.

One more form of iteration is the function, WHILE. WHILE includes a conditional. If the conditional returns true then the body of the WHILE is performed. What makes WHILE an iterative function and one that is different from those above, is that the conditional repeats the test as long as it returns true or nonnil.For example:

(While (Not(Button)) (Print(Getmouse)))

The above performs alot like "Mousey" above. However it all takes place on one line and operates from the mouse differently. Instead of showing the mouse's position with the button down, the above shows until the button is pressed down.

One aspect of ExperLisp which might not be apparent to a novice is the fact that once a procedure is defined via DEFUN, it is available until one quits ExperLisp. ExperLisp is not just a language, it is an environment. If one was to compile all of the samples in this month's issue, then each sample can be run by simply typing the procedure's name within a list in the Listener Window. The value of this fact will be more apparent after the discussion on menus in ExperLisp.

User Warning

In using ExperLisp one must be aware from the very beginning of a bug in Experlisp's design of the user interface. When one tells the Mac to save from the menu selection under "File", ExperLisp saves the active window into the active file. If one has the Listener Window as the active window and tells ExperLisp to save, the entire file will be replaced by the contents of the Listener Window. BE CAREFUL. Check which window is active before you save. Eventually, later versions of ExperLisp will have a "snapshot" feature. This feature will save the contents of the environment. One will be able to get ExperLisp back to exactly where it was when the snapshot was taken without recompiling files. This might be performed by saving with the Listener Window active. If one has a couple of files compiled and is using them in conjunction, this feature will save lots of time when saving and restarting ExperLisp.

Last month I described how one can measure a Lisp machine's capacity by seeing how many cons cells it can handle. I also described the FREECONS procedure available in the latest versions of ExperLisp (v1.02). I'd like to report that after upgrading my 512K Mac to 2 megabytes (from Levco in San Diego) I found that ExperLisp can have as many as 30,440 cons cells. However, that many cons cells is far from necessary for the simple examples contained in the Lisp Listener column. A 512K mac will do fine. In writing this article though, I put Experlisp, Macwrite and Macpaint all into the Switcher utility (v3.5). Most of which I load from a RAMdisk! No more waiting to boot up the applications, verify code, or copy and paste. I have switcher allocate 500K to ExperLisp and I can still access 5000 cons cells. When using the full two megabytes one has as many cons cells as alot of the very expensive Lisp workstations. Note that the upgrades of 1 or 2 megabytes available by most companies do not necessarily access the extra memory in the same way. I can assure all those interested that the 2 megabyte (or Monster Mac) upgrade from Levco can access the extra RAM using ExperLisp or most of the other applications which were designed in accordance with the Macintosh guidelines.

Next month I will show how to use the Mouse in interacting with the Quickdraw routines. I will also discuss recursion.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Trend Micro 11.0.2062 - An essential sec...
Trend Micro Antivirus provides essential security for macOS with real-time malware detection and mitigation in an affordable solution with a simple, intuitive interface. However, be aware that more... Read more
Backblaze 7.0.2.490 - Online backup serv...
Backblaze is an online backup service designed from the ground-up for the Mac. With unlimited storage available for $6 per month, as well as a free 15-day trial, peace of mind is within reach with... Read more
Pro Video Formats 2.2.1 - Updates for pr...
Pro Video Formats includes support for the following professional video codecs: Apple Intermediate Codec Apple ProRes AVC-Intra 50 / 100 / 200 / 4:4:4 / LT AVC-LongG XAVC XF-AVC DVCPRO HD HDV XDCAM... Read more
Boom 3D 1.3.11 - $19.99
Boom 3D is a revolutionary app with 3D Surround Sound and phenomenally rich and intense audio that is realistic and works on any headphones. Features 3D surround sound Built-in audio player... Read more
Final Cut Pro 10.5.2 - Professional vide...
Redesigned from the ground up, Final Cut Pro combines revolutionary video editing with a powerful media organization and incredible performance to let you create at the speed of thought.... Read more
Chromium 89.0.4389.72 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. Version 89.0.4389.72: Complete list of changes can... Read more
iMovie 10.2.3 - Edit personal videos and...
With a streamlined design and intuitive editing features, iMovie lets you create Hollywood-style trailers and beautiful movies like never before. Browse your video library, share favorite moments,... Read more
OmniPlan 4.2.5 - Professional-grade proj...
With OmniPlan, you can create logical, manageable project plans with Gantt charts, schedules, summaries, milestones, and critical paths. Break down the tasks needed to make your project a success,... Read more
Compressor 4.5.2 - Adds power and flexib...
Compressor adds power and flexibility to Final Cut Pro X export. Customize output settings, work faster with distributed encoding, and tap into a comprehensive set of delivery features. Features:... Read more
Motion 5.5.1 - Create and customize Fina...
Motion is designed for video editors, Motion 5 lets you customize Final Cut Pro titles, transitions, and effects. Or create your own dazzling animations in 2D or 3D space, with real-time feedback as... Read more

Latest Forum Discussions

See All

Frogger in Toy Town's latest update...
Konami Digital Entertainment has announced today that their Apple Arcade title Frogger in Toy Town has been updated to introduce a new ranked Endurance Mode. This new game variant's arrival is also accompanied by a few other changes. [Read more] | Read more »
Mitoza is surreal adventure toy you can...
The folks behind the Rusty Lake games have just put a new title onto the App Store. Second Maze, Rusty Lake's collaborative publishing brand, has just brought this 10 year old adventure game from Gal Mamalya to mobile. The best part about all of... | Read more »
Pocket Gamer Awards 2021: You have five...
Three weeks ago our sister site, Pocket Gamer, entered the voting stage for the upcoming Pocket Gamer Awards 2021 and is now in the final stretch. You only have a few hours left to vote for the games you’ve enjoyed on mobile in the past year, as... | Read more »
Patty Stack is a casual arcade game, ava...
Patty Stack is a casual arcade title that's available now for iOS and Android. It's the debut game from developer Feeka Games tasks players with making an increasingly giant burger tower. Think of it as Tower Bloxx but more edible. [Read more] | Read more »
Distract Yourself With These Great Mobil...
There’s a lot going on right now, and I don’t really feel like trying to write some kind of pithy intro for it. All I’ll say is lots of people have been coming together and helping each other in small ways, and I’m choosing to focus on that as I... | Read more »
Genshin Impact Guide - Gacha Strategy: W...
This is part 2 of our Genshin Impact gacha strategy guides. See part 1 here. You can check out more guides for Genshin Impact here. | Read more »
Slashy Camp is a new endless runner insp...
Blue Wizard Digital has released Slashy Camp onto iOS and Android after it spent a short amount of time in early access. [Read more] | Read more »
Kinder World is a relaxing game about lo...
Lumi Interactive is releasing a game called Kinder World later this year on iOS and Android, which is all about looking after houseplants. [Read more] | Read more »
Steam Link Spotlight - Fights in Tight S...
Steam Link Spotlight is a feature where we look at PC games that play exceptionally well using the Steam Link app. Our last entry was on Hades. Read about how it plays using Steam Link over here. | Read more »
Lyxo, the light-based puzzler for mobile...
Vienna-based independent game studio Emoak has just released its unique light-based puzzler for iOS and Android. Founded in 2014 by Tobias Sturn, the company is also the creative force behind the infinite climbing game Paper Climb, as well as the... | Read more »

Price Scanner via MacPrices.net

Weekend Sale: $100 off Apple iPad Magic Keybo...
Amazon has Apple iPad Magic Keyboards on sale for $100 off MSRP for a limited time. Amazon’s prices are the lowest available for iPad Magic Keyboard from any Apple reseller this weekend: – Magic... Read more
Gazelle now offering a full line of refurbish...
Gazelle is now offering a full range of discounted, refurbished, unlocked Apple iPhone 12 models starting at $649. iPhones are offered in Fair, Good, and Excellent conditions, and multiple colors are... Read more
These are the latest discounted iPhones Apple...
Apple has a range of Certified Refurbished iPhones available right now starting at only $339. Apple includes a standard one-year warranty, new outer shell, and shipping is free. According to Apple, “... Read more
Save up to $64 on new M1 MacBook Airs at Expe...
Apple reseller Expercom has 2020 13″ M1 MacBook Airs on sale for $51-$64 off Apple’s MSRP with prices starting at $947.96. In addition to their MacBook Air sale prices, take $50 off AppleCare+ when... Read more
Discounts available on 16″ MacBook Pros with...
Upgrade a 16″ 6-Core or 8-Core MacBook Pro from 16GB of standard RAM to 32GB at Adorama, and save $100-$210 over Apple’s price for this custom option: – 16″ 6-Core MacBook Pro/32GB RAM: $2699, save $... Read more
10.9″ iPad Airs on sale for $50-$70 off Apple...
Amazon has new 2020 10.9″ Apple WiFi iPad Airs in stock and on sale today for up to $70 off MSRP with prices starting at $549. Note that Amazon’s sale price might be restricted to certain colors (see... Read more
Apple restocks 2020 27″ 5K iMacs for up to $3...
After an initial offering in January, Apple has restocked a full line of Certified Refurbished 2020 27″ 5K iMacs starting at $1529 and up to $350 off original MSRP. Apple’s one-year warranty is... Read more
Sale! 16″ 8-Core MacBook Pro for $2449, $350...
Apple reseller Adorama has the 16″ 2.3GHz 8-Core Space Gray MacBook Pro in stock and on sale today for $2449 including free shipping. Their price is $350 off Apple’s MSRP for this model, and it’s the... Read more
Roundup of 13″ Multi-Core Intel MacBook Pro s...
Apple resellers are offering significant sales & deals this week on 2020 13″ MacBook Pros with 10th generation Intel CPUs. Take up to $250 off Apple’s MSRP, get free fast shipping, and/or pay no... Read more
64GB iPhone 8 Plus available for $379 at Appl...
Apple has the 64GB iPhone 8 Plus in Space Gray & Gold colors available for $379 today, Certified Refurbished. Each phone is unlocked and comes with Apple’s standard 1-year warranty and free... Read more

Jobs Board

Geek Squad Advanced Repair *Apple* Professi...
**795178BR** **Job Title:** Geek Squad Advanced Repair Apple Professional **Job Category:** Store Associates **Store Number or Department:** 001406-Allen Park-Store Read more
Geek Squad *Apple* Consultation Professiona...
**796549BR** **Job Title:** Geek Squad Apple Consultation Professional **Job Category:** Store Associates **Store Number or Department:** 001800-Hot Springs-Store Read more
*Apple* Mobility Specialist - Best Buy (Unit...
**796014BR** **Job Title:** Apple Mobility Specialist **Job Category:** Store Associates **Store Number or Department:** 001776-Woodmore Towne Centre-Store **Job Read more
Systems Architect, *Apple* Production Engin...
…package beginning on your first day? If so, we hope you'll keep reading! The Apple Sales Engineering and account team is looking for a stellar presales engineer with Read more
Systems Engineer, Webscale, *Apple* Retail,...
…beginning on your first day? If so, we hope you'll keep reading! The Apple Sales Engineering team is looking for a pre-sales engineer with Enterprise engineering Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.