How does following code work? This code is from Racket documentation https://docs.racket-lang.org/plot/renderer2d.html?q=2d%20renderers#%28part.2.D.Line_.Renderers%29 (see function points on this page). This is not usual function definition statement. What does the underscore stand for here?
(define xs (build-list 5 (λ _ (random))))
The xs gets following value:
> xs
'(0.9520057193043618 0.1339193598495859 0.0019128879992944899 0.7511052254656998 0.4442323053722083)
A lambda can either have a list of identifiers as parameter names (such as (lambda (a b c) the-body )) or a single identifier (such as (lambda args the-body), which will then hold the list of all arguments.
The function given to build-list takes one parameter (the current index). It is customary to name parameters _ when you don't intend to use their value.
So since we don't care about the current index when creating a random list, the parameter is named _. This could also be written as (lambda (_), but since we don't care about any of the (one) parameters, we can just write (lambda _ as well.
Related
I'm having a hard time understanding the syntax of let vs some of the other statements. For example, a "normal" statement has one parentheses:
(+ 2 2)
$2 = 4
Yet the let statement has two:
(let ((x 2)) (+ x 2))
$3 = 4
Why is this so? I find it quite confusing to remember how many parentheses to put around various items.
Firstly, note that let syntax contains two parts, both of which can have zero or more elements. It binds zero or more variables, and evaluates zero or more forms.
All such Lisp forms create a problem: if the elements are represented as a flat list, there is an ambiguity: we don't know where one list ends and the other begins!
(let <var0> <var1> ... <form0> <form1> ...)
For instance, suppose we had this:
(let (a 1) (b 2) (print a) (list b))
What is (print a): is that the variable print being bound to a? Or is it form0 to be evaluated?
Therefore, Lisp constructs like this are almost always designed in such a way that one of the two lists is a single object, or possibly both. In other words: one of these possibilities:
(let <var0> <var1> ... (<form0> <form1> ...))
(let (<var0> <var1> ...) (<form0> <form1> ...))
(let (<var0> <var1> ...) <form0> <form1> ...)
Traditional Lisp has followed the third idea above in the design of let. That idea has the benefit that the pieces of the form are easily and efficiently accessed in an interpreter, compiler or any code that processes code. Given an object L representing let syntax, the variables are easily retrieved as (cadr L) and the body forms as (cddr L).
Now, within this design choice, there is still a bit of design freedom. The variables could follow a structure similar to a property list:
(let (a 1 b 2 c 3) ...)
or they could be enclosed:
(let ((a 1) (b 2) (c 3)) ...)
The second form is traditional. In the Arc dialect of Lisp designed Paul Graham, the former syntax appears.
The traditional form has more parentheses. However, it allows the initialization forms to be omitted: So that is to say if the initial value of a variable is desired to be nil, instead of writing (a nil), you can just write a:
;; These two are equivalent:
(let ((a nil) (b nil) (c)) ...)
(let (a b c) ...)
This is a useful shorthand in the context of a traditional Lisp which uses the symbol nil for the Boolean false and for the empty list. We have compactly defined three variables that are either empty lists or false Booleans by default.
Basically, we can regard the traditional let as being primarily designed to bind a simple list of variables as in (let (a b c) ...) which default to nil. Then, this syntax is extended to support initial values, by optionally replacing a variable var with a (var init) pair, where init is an expression evaluated to specify its initial value.
In any case, thanks to macros, you can have any binding syntax you want. In more than one program I have seen a let1 macro which binds just one variable, and has no parentheses. It is used like this:
(let1 x 2 (+ x 2)) -> 4
In Common Lisp, we can define let1 very easily like this:
(defmacro let1 (var init &rest body)
`(let ((,var ,init)) ,#body))
If we restrict let1 to have a one-form body, we can then write the expression with obsessively few parentheses;
(let1 x 2 + x 2) -> 4
That one is:
(defmacro let1 (var init &rest form)
`(let ((,var ,init)) (,#form)))
Remember that let allows you to bind multiple variables. Each variable binding is of the form (variable value), and you collect all the bindings into a list. So the general form looks like
(let ((var1 value1)
(var2 value2)
(var3 value3)
...)
body)
That's why there are two parentheses around x 2 -- the inner parentheses are for that specific binding, the outer parentheses are for the list of all bindings. It's only confusing because you're only binding one variable, it becomes clearer with multiple variables.
I saw a question which asked about a contract of a method in a pet language known as let.The language is not important but does contract means that
things that the method takes as an argument and its value after evaluating?
(define extend-env*
(lambda (syms vals old-env)
(if (null? syms)
old-env
(extended-env-record
(car syms)
(car vals)
(extend-env* (cdr syms)
(cdr vals)
old-env)))))
So in here the method takes a symbol a value and an environment and I think it produces a new environment.
Does that mean contract for this method is Identifier(Variable),Value,Environment = Environment ?
Your functions starts like this:
(lambda (syms vals old-env) ...)
Here sym stand for symbol and thus syms stands for a list of syms aka a list of symbols. In the same manner vals stands for a list of values. Finally old-env is an environment.
This covers the input to the function. To confirm that syms is supposed to be a list of symbols, look at how syms is used in the body. We see thee uses: (null? syms), (car syms), and, (cdr syms). This means we guess correctly.
To see type of the output, look for the expression(s) that produce return values.
The simplest is old-env which is an environment. If the function always returns the same type of value, we have determined that the output is an environment. It best to check that the other return expressions also return environments though.
To sum up: the contract seen from Racket is:
extend-env* : list-of-symbols list-of-values environment -> environment
Now in your program the symbols represent identifiers, so you could also write:
extend-env* : list-of-identifiers list-of-values environment -> environment
if you document that identifiers are represented as symbols.
I'm trying to create a function that will take a string and display it.
(defun closing (s)
(format t "~{~a~}" ("Sincerely," "\n" s)))
What I hope to get is
Sincerely,
Frank
if "Frank" is the string I passed in. It complains of the variable S is defined but never used. What am I doing wrong?
Trying to use format alone: If I declare urname as a defparameter to be "Frank", the following doesn't print Frank, rather just the variable name. (Without quote it complains of urname not being a function.)
(format t "~{~a~}" '(urname urname urname))
How can I feed variables to format?
There are three issues here: (1) The code you posted doesn't just have the problem of not using s; it's also trying to call the string "Sincerely" as a function; (2) quoting a list means you'll get exactly what's quoted (e.g., a list of symbols, not a list of values of variables); (3) calling format with lists.
(something other-stuff...) is a function call
When I put the code you posted into SBCL, I get some very specific and helpful output:
CL-USER> (defun closing (s)
(format t "~{~a~}" ("Sincerely," "\n" s)))
; in: DEFUN CLOSING
; ("Sincerely," "n" S)
;
; caught ERROR:
; illegal function call
; (SB-INT:NAMED-LAMBDA CLOSING
; (S)
; (BLOCK CLOSING (FORMAT T "~{~a~}" ("Sincerely," "n" S))))
;
; caught STYLE-WARNING:
; The variable S is defined but never used.
;
; compilation unit finished
; caught 1 ERROR condition
; caught 1 STYLE-WARNING condition
("Sincerely," "\n" s) is an illegal function call, since a string, like "Sincerely", can't have a function binding. Since SBCL sees the problem in that, it recognizes that the one thing that s might have been used for (i.e., an argument to a function call), can't happen. That's why you'll get the error, and then the associated style warning.
Creating lists of values
The second is probably answered in other questions already, but the short answer is that you want (list x y z), not '(x y z). The former calls the function list with the values of the variables x, y, and z, while the latter denotes a literal list of the symbols x, y, and z.
CL-USER> (let ((a 42)
(b 89))
(print '(a b)) ; a list of two symbols
(print (list a b))) ; a list of two numbers
(A B)
(42 89)
Format, iteration, &c.
The third is probably more interesting, since format has so many possibilities. The ~{ and ~} in your example are used for iterating over values in a list. First, let's look at a simple example: you can just use the format directive ~a and call format with the arguments you want to splice in:
CL-USER> (let ((closing "Sincerely")
(name "Frank"))
(format t "~a,~%~a" closing name))
Sincerely,
Frank
Now, if you need to print multiple values, you can use ~{ and ~} to have format iterate over a list of values:
CL-USER> (let ((closing "Sincerely")
(names '("Frank" "John")))
(format t "~a,~{~%~a~}" closing names))
Sincerely,
Frank
John
If the names are the values of variables, then you can either create a list containing those values:
CL-USER> (let ((closing "Sincerely")
(name1 "Frank")
(name2 "John"))
(format t "~a,~{~%~a~}" closing (list name1 name2)))
Sincerely,
Frank
John
or you can change ~{ to ~#{ and have format read the remaining arguments as the list:
CL-USER> (let ((closing "Sincerely")
(name1 "Frank")
(name2 "John"))
(format t "~a,~#{~%~a~}" closing name1 name2))
Sincerely,
Frank
John
You should read a tutorial about format, from here for example
For an easy explanation
(format
(destination-stream usually t for standard output nil to form a string)
(here comes the string)
(&rest variables that should write in the string where is an ~A and by position like String.format in java or c))
in your case, you need the symbol ~% or use the character for return in common lisp
CL-USER> (defun closing (s) (format t "~A~%~%~A" "Sincerely," s))
CLOSING
CL-USER> (closing "paco")
Sincerely,
paco
NIL
The nil say that the functions returns null, and the other is the standard output if you want to return a string, put nil instead of t
When I evaluate the following expression every time I get the value 10.
(((lambda (x) (lambda () (set! x (+ x 10)) x)) 0))
However I just modify by abstracting the above procedure with a name and call foo every time the value increments by 10!!
(define foo ((lambda (x) (lambda () (set! x (+ x 10)) x)) 0))
Can anybody please explain this?
The function you are calling is a counter that returns a number 10 higher every time it's called.
In the first case, every time, you are creating a new function and then immediately calling it once and then discarding the function. So every time, you are calling a new instance of this counter for the first time, so it should return 10.
In the second case, you create the function once and assign it to a variable and call that same function repeatedly. Since you are calling the same function, it should return 10, 20, ...
newacct is correct, but I would like to go into (a lot) more detail, since this is something that just blew my mind pretty recently.
I'm going to use the terms 'environment' and 'scope' pretty loosely and to mean essentially the same thing. Remember that scheme is a lexical scope language.
When scheme evaluates an expression it will look in its current environment for the values of any variables in the expression. If it doesn't find any in the current environment, it will look in the parent environment. If the value is not in the parent environment then it will look in the next level up and so on until it reaches the top (global) level where it will either find the value or throw an "unbound variable" error.
Anytime you call define you associate a symbol with a value on that environments symbol table. So if you call define on the top-level an entry will be added to the global symbol table. If you call define in the body of a procedure, then an entry will be added to the symbol table of that procedure.
A good way to think about calling define on a procedure is that you are creating an entry in the symbol table that consists of the parameters, body, and environment of that procedure. For example the procedure square would have an entry something like this:
(define a 3)
(define (square x)
(* x x))
GLOBAL
=================
a-|-3
|
square-|-{x}
| {(* x x)}
| {GLOBAL} ---> All the things defined on the global table
Then if I were to call (square a) the interpreter would first look in the environment in which square is defined and it would find that a is associated with the value 3. Then x -> 3 within the body of square and the procedure returns 9. Cool, makes sense.
Things get a little screwier when we start defining helper procedures within procedures, but all you really need to remember is that if it can't find anything associated with a symbol in the current environment, it will move up levels of scope until it does. Also, it will always stop on the first 'match'. So if there is a local x it will prefer it over the global x (rather it will use the local x without ever looking for a global one).
Next, remember that define just adds names to the symbol table, but set! is a mutator that actually changes the values with which a symbol is associated.
So (define b "blah") puts an entry in the symbol table. b => "blah". Nothing crazy. set! will change the actual value:
(set! b "foo")
b => "foo"
but set! can't add anything to the table. (set! c "bar") => UNBOUND VARIABLE C.
This is the most important difference: set! acts like any other procedure in that if it doesn't find the variable in the current scope, it will check progressively higher levels until it finds a match (or throws an error), but define always adds a binding to the scope in which it is called.
Alright, so you understand the difference between define and set!. Good. Now on to the question.
The expression (((lambda (x) (lambda () (set! x (+ x 10)) x)) 0)), as newacct pointed out, is going to return the same value each time because you are calling a new procedure each time. However if you name it you can keep track of the environment created by calling the procedure.
(define foo <--- associated name on the symbol table
(lambda (x) <--- scope where x is defined
(lambda () \
(set! x (+ x 10)) |--- body
x)) /
0) <--- initial value of x
So the inner lambda exists inside the environment created by the first one where the symbol x exists at an initial value of 0. Then set! looks for an entry in the symbol table for x and finds one in the next level up. Once it finds the entry it changes it, in this case adding 10 to whatever value it finds there. The really cool part is that since you associated the whole thing to a name in the global symbol table, that environment continues to exist after each call! This is why we can do cool things like implement message passing objects to keep track of and manipulate data!
Also, the let special form was created for this purpose, and may be a more intuitive way to structure this. It would look like this:
(define foo <--- associated name
(let ((x 0)) <--- scope where x is defined & initial x value
(lambda () \
(set! x (+ x 10)) |--- body
x))) /
I have see the following code... The first call of (next-num) returns 1, and the second returns 2.
(define next-num
(let ((num 0))
(lambda () (set! num (+ num 1)) num)))
(next-num) ; 1
(next-num) ; 2
What I can not understand is... num is created by let inside next-num, it is kind of a local variable... How does scheme know that each time next-num is called, the value of num is not erased by let ((num 0)); How does scheme know that it is always the same num that we modify whenever next-num is called?
It seems that num is both local and static... How can we define a local variable, but not static?
This is "lexical closure" and you're right that num, the "closed-over variable" is similar to a static variable, in C for example: it's only visible to code within the let form (its "lexical scope"), but it persists across the whole program run, rather than being re-initialized with each call to the function.
I think the part you're confused on is this: "num is created by let inside next-num, it is kind of a local variable". This isn't true because the let block isn't part of the next-num function: it's actually an expression which creates and returns the function which is then bound to next-num. (This is very different, e.g., from C, where functions can only be created at compile-time and by defining them at top-level. In Scheme, functions are values like integers or lists, which any expression can return).
Here's another way to write (almost) the same thing which makes it clearer that the define is just associating next-num to the value of a function-returning expression:
(define next-num #f) ; dummy value
(let ((num 0))
(set! next-num
(lambda () (set! num (+ num 1)) num)))
It's important to note the difference between
(define (some-var args ...) expression expression ...)
which makes some-var a function which executes all the expressions when called, and
(define some-var expression)
which binds some-var to the value of expression, evaluated then and there. Strictly speaking, the former version is unnecessary, because it's equivalent to
(define some-var
(lambda (args ...) expression expression ...))
Your code is almost the same as this, with the addition of the lexically scoped variable, num, around the lambda form.
Finally, here's a key difference between closed-over variables and static variables, which makes closures much more powerful. If you had written the following instead:
(define make-next-num
(lambda (num)
(lambda () (set! num (+ num 1)) num)))
then each call to make-next-num would create an anonymous function with a new, distinct num variable, which is private to that function:
(define f (make-next-num 7))
(define g (make-next-num 2))
(f) ; => 8
(g) ; => 3
(f) ; => 9
This is a really cool and powerful trick which accounts for a lot of the power of languages with lexical closures.
Edited to add: You ask how Scheme "knows" which num to modify when next-num is called. In outline, if not in implementation, this is actually pretty simple. Every expression in Scheme is evaluated in the context of an environment (a lookup table) of variable bindings, which are associations of names to places which can hold values. Each evaluation of a let form or a function call creates a new environment by extending the current environment with new bindings. To arrange to have lambda forms behave as closures, the implementation represents them as a structure consisting of the function itself plus the environment in which it was defined. Calls to that function are then evaluated by extending the binding environment in which the function was defined -- not the environment in which it was called.
Older Lisps (including Emacs Lisp until recently) had lambda, but not lexical scope, so although you could create anonymous functions, calls to them would be evaluated in the calling environment rather than the definition environment, and so there were no closures. I believe Scheme was the first language to get this right. Sussman and Steele's original Lambda Papers on the implementation of Scheme make great mind-expanding reading for anyone who wants to understand scoping, among many other things.