TweetFollow Us on Twitter

Functions in Lisp
Volume Number:1
Issue Number:8
Column Tag:Lisp Listener

"Functions in Lisp"

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

Defining Procedures

As you may recall from the first installment of the Lisp Listener, a procedure is a description of an action or computation. A primitive is a predefined or "builtin" procedure (e.g. "+"). As in Forth, Lisp can have procedures which are defined by the programmer. DEFUN, from DEfine FUNction, is used for this purpose. The syntax for DEFUN in Experlisp is as follows:

(DEFUN FunctionName (symbols) 
          (All sorts of computations which may or may Not use the values 
represented by  the symbols))

The function name is exactly that. Whenever the name is used the defined procedure associated with that function name is performed. The symbols are values which may or may not be required by the procedures within the defined function. If required, the values must follow the function name. When given, these values are assigned to the symbol. This is similar to the way values are assigned to a symbol when using SETQ. It is easier to see how DEFUN works when observed within an example:

;(DEFUN Reciprocal (n)
 (/ 1 n))
;Reciprocal
;(Reciprocal 5)
;.2 
;(Reciprocal 2384)
;.000419463 

The word "Reciprocal" is the function name and the numbers following are the values for which the reciprocal (1/n) are found. After the list containing DEFUN is entered and the carriage return is pressed the function and it's title are assigned a location in memory. The function name is then printed in the Listener window.

;(DEFUN Square (x)
 (* x x))
;Square
;(Square 5)
;25

;(DEFUN Cubed (y)
 (* y (* y y))
;Cubed
;(Cubed 5)
;125

;(DEFUN AVERAGE (W X Y Z)
  (/ (+ W X Y Z) 4)) 
;Average
;(Average 2 3 4 5)
;3.5

You might recognize "Average" from last month's Lisp Listener. One might imagine using defined functions inside other defined functions. If it was possible to have variables which have the same values in each procedure, then the version of Lisp used has what is called dynamic scoping. In this context the values of the variable are determined by the Lisp environment which is resident when the procedure is called. Experlisp, however, is lexically scoped. That means that variable values are local to each procedure. Two defined procedures can use the same labels for variables, but the values will not be considered as the same. Each variable is defined locally. This is in accordance to the Common Lisp standard. Lexical scoping makes it easier to debug someone elses'' programs. If you don't know what I mean yet, don't worry. This subject will come up again in more detail later.

Predicates

If no values are required by the defined function then "nil" or an empty list must follow the function name.

;(DEFUN Line ()
 (Forward 50))

The empty list obviously contains no atoms (I'll describe the above function, "Line" later in the section on bunnies). It is synonymous to the special term nil, which is considered by Lisp as the opposite of T or True. Nil is used in many other contexts.

;(cddr '( one two)) 
;nil              

In the above, the first cdr returns "two". The second cdr returns nothing, hence "nil". The values of true and false are returned by procedures called predicates. While nil represents a false condition, anything other then nil, including "T", is generally considered true. Please note that I used lowercase letters in the above. ExperLisp recognizes both upper and lowercase. I've been using uppercase only to make it clear within the text when I'm referring to Lisp

EQUAL is a predicate which checks the equality of two arguments. Note the arguments can be integers or symbols. If the two arguments are equal then "T" is returned. If they are not equal then "nil" is returned.

;(EQUAL try try)
;T

;(EQUAL 6732837 6732837)
;T

;(EQUAL 6732837 6732833)
;nil

;(EQUAL First Second)
;nil

ATOM checks to see if it's argument is a list or an atom. Remember, the single quote is used to indicate that what follows is a not evaluated as in the case of a list. Symbols are evaluated.

;(ATOM 'thing)
;T

;(ATOM thing)
;nil

;(ATOM (A B C D))
;nil

In the first of the above 'thing is an atom due to the single quote. In the second, thing is considered a symbol. A symbol is evaluated and contains a value or values as a list. In the third, (A B C D) is obviously a list.

LISTP checks if it's argument is a list.

;(LISTP '( 23 45 65 12 1))
;T

;(SETQ babble '(wd ihc wi kw))
;(LISTP babble)
;T
;(LISTP 'babble)
;nil

;(LISTP 'thing)
;nil

One interesting observation is that nil is both an atom and a list, ()=nil. Therefore ATOM and LISTP both return true for nil.

;(ATOM ())
;T


;(LISTP ())
;T

When one needs to know if a list is empty, NULL does the job.

;(NULL good)
;nil

;(NULL (X Y Z))
;nil

;(NULL ())
;T

;(NULL nil)
;T

NUMBERP checks if the argument that follows is or represents a number rather than a string.

;(NUMBERP 56.887)
;T

;(NUMBERP fifty-six)
;nil

;(SETQ fifty-six '(56))
;(NUMBERP fifty-six)
;T

Now for a real slick one. MEMBER tests whether or not an argument is a part of a list. An easy demonstration follows:

;(MEMBER 'bananas (apples pears  bananas))
;(apples pears bananas)
;(MEMBER 'grapes (apples pears bananas))
;nil
    

When the argument is a member, then the contents of the list are given. If not then nil is returned. MEMBER also checks symbols of lists.

;(SETQ fruit '(apples grapes pears))
;(MEMBER 'grapes fruit)
; (apples grapes pears)
;(MEMBER 'banana   fruit)
;nil

EVENP tests to see if an integer is even and MINUSP checks if an integer is negative. ODDP and PLUSP are not needed since they are simply opposite of the first two.

;(EVENP 2)
;T

;(EVENP (- 806 35))
;nil

;(MINUSP 25)
;nil

;(MINUSP (-34 86))
;T

In the second and fourth examples above the lists contained within are calculated prior to MEMBERP evaluation. (806-35=771 & 34-86=-52. There's a few more simple predicates such as NOT, <, >, and ZEROP. I'll discuss them along with conditionals next month. Now for something completely different.

Bunny Graphics

If you've ever learned Logo, the concept of Bunny graphics should sound familiar. As mentioned last month, the Bunny is Expertelligence's version of the Turtle. All one needs to do in order to make a Bunny move is to tell it to. FORWARD X initially moves the Bunny upwards on the screen for 'X' display pixels. A negative number initially moves it down. When one enters the following in the Listener window,

;(FORWARD 50)

the default graphics window (I'll discuss windows in more detail very soon in future installments) is then opened and the following is drawn:

RIGHT X aims the front of the line to the right by X degrees. If one then uses forward again the line moves in a different direction. For example:

 ;((RIGHT 50) (FORWARD 50))

or better yet

;(DEFUN Line 
 (RIGHT 50) (FORWARD 50))
;Line
;(Line)

After a line is moved, the end of the line remains where it was. If one made the Bunny move again the beginning of the new line would begin where the old left off. The original starting point is the graphics window default home position. This position is in the center of each graphics window when the window is first created. In order to return the Bunny to the original starting point one must use HOME.

;(HOME)

The following produces a much neater triangle:

(DEFUN Triangle ()
         (Penup) (Left 45)
         (Forward 10) (Pendown)
        (Right 90) (Forward 25)
        (Right 90) (Forward 50)
        (Right 135) (Forward 71)
       (Right 135) (Forward 25))

After the above is typed into the edit buffer the "Compile All" selection should be chosen from the Menu Bar. The source code in the Edit Buffer quickly inverts to white letters on a black background as if the whole file was selected for a moment. The function name "Triangle is then printed in the Listener window. If the user enters the following in the Listener Window a different triangle is drawn in the default Graphics Window:

;(Triangle)

If you Look at the in Triangle you will see a couple more Bunny commands. LEFT does the same as RIGHT but in the opposite direction. PENUP raises the Bunny's pen so that when the Bunny moves no lines are drawn. PENDOWN returns the Bunny to the drawing orientation. The first line of code in "Triangle" puts the Bunny off the Home position so that the drawn triangle will be centered on the screen. As mentioned earlier, the orientation of the bunny remains. The last line of code in "Triangle left the Bunny aimed at about 1:00 rather than the initial position, 12:00. If we were to make "Triangle" execute ten times without eliminating the Graphics Window the following would result:

In getting "Triangle" to execute recompilation of the code in the edit buffer is not necessary. To get the above one can type the function name into a list ten times within the Listener window. The following however, is easier:

;(Dotimes (a 10) (Triangle))

DOTIMES is very similar to the FOR...NEXT looping routine in BASIC. I'll discuss it next month in a description of iteration and recursion in ExperLisp.

If we wanted to use a three dimensional bunny then the following would be added before "Triangle" in the Edit Buffer window:

(SETQ curbun (new3dbun))
(Pitch 30) (Yaw 45) (Roll 50)

Something like the following is drawn after the source code is recompiled and "(Triangle)" is entered into the Listener Window:

CURBUN is a special symbol in ExperLisp which always refers to the Bunny cursor. NEW3DBUN is a special term which always changes CURBUN. The default Bunny is 2 dimensional. If one wanted the Spherical Bunny then the following would be entered into the beginning of the first version of "Triangle":

(SETQ curbun (newspbun))

This would then produce what follows:

In order to have the above drawn in a different orientation, different Bunny direction would be required. Windows, two and three dimensional Bunny graphics and toolbox graphics use the same X,Y coordinate system. Home is 0,0. Dual negative coordinates are situated towards the upper left corner. Dual positive coordinates are situated towards the lower right corner. The range is +32767 to -32768 for each dimension. In ExperLisp one can sometimes use the third dimension, as in the 3D sample of "Triangle". Negative Z values are behind Home, while positive Z values are in front. The following illustrates the coordinate system in ExperLisp:

Compiler Information

The ExperLisp disk contains three essential files; Compiler, LispENV and Experlisp. Compiler is not actually the entire Lisp compiler. It contains the information needed in generating all of the higher level Lisp syntactics, such as the Bunny graphics. LispENV stands for Lisp Environment and it is simply a duplication of Compile. LispENV contains information on how the Macintosh memory was organized by the programmer and ExperLisp during the previous session. It also contains information on the system configuration such as the number of disk drives, the amount of memory, etc. Sometimes LispENV can be messed up (i.e. by changing the variable table). When this happens one might not be able to start ExperLisp. In this case LispENV should be removed from the disk. Afterward, when ExperLisp is opened, Compiler generates a new LispENV. Compiler is not needed on the disk unless the LispENV is ruined. Deleting it will provide 100K more space on the disk. Before eliminating it from the disk however, be sure you have a backup as it is an essential file. The Experlisp file contains the assembly language routines which represent the lower level Lisp routines like CAR and CDR. It also allows access to the Macintosh toolbox routines and contains the Listener Window. One opens the Experlisp file in starting a programming session with ExperLisp. Another file on the disk is automatically loaded and activated when Experlisp is booted. It is labeled ªlispinit. The contents of this file can be added to so that when one boots up ExperLisp a program can be automatically executed. It can also do automatic configurations. However the contents of ªlispinit should not be changed since it configures the Macintosh memory for Exper- Lisp.

Next month I'll discuss a few more predicate procedures. I also hope to start discussing iteration, recursion and conditionals. If there is enough room left over I might also begin discussing how to access the toolbox graphics.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.