Step 1 showed a complete program. This lesson takes apart the small set of shapes inside it. A value is one thing, a name that refers to a value is another, and a procedure call that computes a value is a third. Keeping those three apart is most of the work.
Values can stand alone
Numbers, booleans, strings, characters, and quoted data are values.
42
#t
"Lispex"
#\L
'readyTo write a single character as a value, put #\ in front of it. The #\L above
is one capital L. That is a different kind of value from a string in double
quotes.
A bare symbol such as ready behaves differently. Written without a quote,
ready is a name that Lispex looks up. Writing 'ready instead preserves the
symbol as data.
A list in call position asks for work
You can read this one by starting at the innermost call and working outward.
(+ 10 (* 2 3))First Lispex finds +, then evaluates 10, then evaluates (* 2 3) from
left to right. The inner call produces 6, so the outer call becomes the
equivalent of (+ 10 6).
Result
16Some parenthesized forms are not ordinary calls. define, lambda, let, and
if control which parts are evaluated and where names are visible. The syntax
map calls out each of these forms explicitly.
Give a value a name
define creates or updates a top-level binding, meaning a name the rest of the
file can use.
(define fee 3)
(+ 20 fee)Result
23The definition itself prints nothing. The final addition prints one value.
Reach for let when a name is needed only inside one body.
(let ((base 7))
(* base 2))Result
14The binding base is visible inside the body and disappears afterward. That
small scope makes a temporary calculation easier to inspect.
Create a reusable procedure
Function-definition shorthand lets you name both the procedure and its inputs at once.
(define (price-with-fee price fee)
(+ price fee))
(price-with-fee 20 3)Result
23Writing out the equivalent long form makes the procedure value visible.
(define price-with-fee
(lambda (price fee)
(+ price fee)))A procedure checks how many arguments it was given. Calling price-with-fee
with one or three arguments is a runtime error rather than an implicit default.
Put the pieces together
(define (price-with-fee price fee)
(+ price fee))
(list (price-with-fee 20 3)
(let ((base 7))
(* base 2)))Result
(23 14)Notice the order here. The first list element is computed, then the second.
list receives the two resulting values and constructs (23 14).
Exercise
Define a procedure named triple that multiplies its input by 3, then return
(12 21) by calling it twice inside list.
Show one answer
(define (triple n)
(* n 3))
(list (triple 4) (triple 7))Ready for Step 3?
Continue when you can explain why a quoted symbol is data, why (* 2 3) runs
before the outer addition uses it, and where a let name is visible. Next comes
Code Is Data.