This blog will discuss:
- declaring and using variables in LISP
- declaring and using constants in LISP
- Arithmetic operators in LISP
We'll be doing the programming in this post using the Listener in LispWorks Personal Edition.
First, we'll declare a variable, x and assign it a value of 10 - seen below. As well as declaring it, we have the Listener print the value of the variable using the write function, then again by simply calling the variable name in the command line:
As you can see, the syntax in LISP is unique. Essentially when declaring a variable using the defvar function, it breaks down like so: ( defvar [name of variable] [value of variable])
Here are two more examples as we declare variables y and z.
Next let's do some math. First, let me exemplify the four basic operators, addition, subtraction, multiplication, and division. The syntax in LISP can be confusing when using arithmetic operators.
Here are some examples, notice that the operator comes first. When the line is read, it continues to do the operation until every value is read.
Next, we will declare a variable, total, and assign it the value of x + y + z:
We then call the variable so that the value can be printed, showing that we have the correct total.
Next, we'll find the average of the three values by declaring another variable, avg, using the division function to divide the total by 3, then calling the variable we created, avg.
Everything checks out okay!
Now we're going to declare a constant using the defconstant function. Let's define the constant gravity at 9.8 m/s^2 and then we'll do some physics calculations with it.
Let's look at the general formula for velocity with respect to time: v = gt, where v is velocity, g is gravity, and t is time. As an example of LISPs arithmetic abilities, let's pretend our variables x, y, and z are times in seconds, and our constant gravity will act as gravity. We can then find the velocity of any object at the times 10, 20, and 30 using variables x, y, and z respectively.
That's all for today, I hope you enjoyed.
If you have any questions, feel free to leave a comment below.
Peter Short, CS 270, February 10, 2016, Blog #3
I see that constants and variables are declared differently, but I did not get a sense of how they differ - for example, as we've discussed on the Google page - does Lisp allow you to change the value of a variable?
ReplyDeleteIn Lisp, variables can be reassigned their value using the setq function. This is briefly discussed and an example is given in my most recent post.
Delete