What is the Common Lisp equivalent of the Scheme default-object? [duplicate] - scheme

This question already has an answer here:
Distinguish &optional argument with default value from no value
(1 answer)
Closed 6 years ago.
I am converting some Scheme code to Common Lisp. I don't know Scheme. I know a bit of Common Lisp.
Here is the Scheme code:
(define (close-enuf? h1 h2 #!optional tolerance scale)
(if (default-object? tolerance)
...))
I converted that Scheme code to this Common Lisp:
(defun close-enuf? (h1 h2 &optional tolerance scale)
(if (xxx tolerance)
...))
Aside from xxx, does that look right?
Now, with regard to xxx, what is the Common Lisp equivalent for default-object?
I found this definition of default-object?:
The predicate default-object?, which is true only of default objects, can be used to determine which optional parameters were supplied, and which were defaulted.
I'm not sure what that is saying. Is it saying that default-object? returns true if the argument's value is the default value (not a passed-in value)?

This is covered in the Ordinary Lambda Lists section of the specification:
lambda-list::=
(var*
[&optional {var | (var [init-form [supplied-p-parameter]])}*]
[&rest var]
[&key {var | ({var | (keyword-name var)} [init-form [supplied-p-parameter]])}* [&allow-other-keys]]
[&aux {var | (var [init-form])}*])
The &optional arguments can be single symbols or a list with two or three elements.
In that case, the second value is the default value.
The third value names a variable which holds a boolean value: it is true if and only if the value bound to var was supplied by the caller.
Otherwise, a NIL indicates that the value is the default one.
For example:
(defun foo (&optional (x 1 xp))
(list x xp))
With no argument supplied:
(foo)
=> (1 nil)
With an explicit argument:
(foo 2)
=> (2 T)
With an argument that is indistinguishable from the default value:
(foo 1)
=> (1 T)
In your case, that would be:
(defun close-enough-p (h1 h2 &optional (tolerance nil tolerance-p) scale)
(if tolerance-p
<supplied>
<default>))
Note that the same goes for &key arguments.

Related

Understanding parentheticals on let

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.

Lisp format list with parameter

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

Determine definition and parameter of a Scheme function in the interpreter? / How are functions stored in Scheme?

I want to create a function that can determine the definition of an arbitrary function in scheme. If we call such a function "definition", it would work as such:
(define (triple x) (* 3 x))
(definition triple) would return "(triple x) (* 3 x)".
There would be some implementation problems (such as with n-arity), but I'm concerned mostly with whether or not the definition of individual functions are easily retrievable in Scheme.
As a continuation, is there a way to create a function that can determine the parameters of an arbitrary function? Such that:
(parameters +) returns (number number) or something similar.
These questions both fall under the question of how functions are stored in Scheme - I found some sources which claimed that function definitions are stored with the function name, but I couldn't find out how exactly they were stored.
If this is impossible - is there a language where function definitions are easily retrievable?
There is nothing like that in Scheme. Individual implementations might have that, though.
In Common Lisp there is the standard function function-lambda-expression, which might be able to retrieve source code - depending on the implementation.
Example in LispWorks (reformatted to improve readability here):
CL-USER 65 > (defun triple (x) (* 3 x))
TRIPLE
CL-USER 66 > (function-lambda-expression #'triple)
(LAMBDA (X)
(DECLARE (SYSTEM::SOURCE-LEVEL #<EQ Hash Table{0} 42201D392B>))
(DECLARE (LAMBDA-NAME TRIPLE))
(* 3 X))
NIL
TRIPLE
SBCL:
* (defun triple (x) (* 3 x))
TRIPLE
* (function-lambda-expression #'triple)
(SB-INT:NAMED-LAMBDA TRIPLE
(X)
(BLOCK TRIPLE (* 3 X)))
NIL
TRIPLE
As you can see it returns three values: the code, whether it is a closure and the name of the function.

How is 'and' defined in Scheme?

'and' in Scheme will ignore the error 'division by 0', like (and (negative? (random 100)) (/ 1 0)) returns #f.
How does it do that?
i (define (∧ b₀ b₁) (if (not b₀) #f b₁)), (∧ (negative? (random 100)) (/ 1 0)) still goes into a 'division by 0' error.
You can't define and directly as a function because Scheme is strict--this means that function arguments are always evaluated before being passed to the function.
However, you can define a proper short-circuiting and using a macro. Here's the simplest version in Racket:
(define-syntax-rule (my-and a b) (if a b #f))
or the equivalent form using syntax-rules which is in standard Scheme:
(define-syntax my-and
(syntax-rules ()
[(_ a b) (if a b #f)]))
A macro is not a normal function. Instead, it's a syntactic transformation that runs at compile-time. When you use your new and in your code, it gets "expanded" to the corresponding if expression. So:
(my-and #f (/ 1 0))
gets transformed into
(if #f (/ 1 0) #f)
before your program is run. Since if is built into the language, this has the correct behavior.
Since macros are not functions, it also means you can't pass around as arguments. So you can't write a fold using and directly--you'd have to wrap it into a lambda.
To be more faithful to the original and, you could define my-and to take an arbitrary number of arguments by making the macro recursive. To define a "rest parameter" in a macro, you use the special ... keyword:
(define-syntax my-and
(syntax-rules ()
[(_) #t]
[(_ a) a]
[(_ a b ...) (if a (my-and b ...) #f)]))
If you were using a lazy language like Racket's #lang lazy or Haskell instead, you would not need to use macros here. You could just define and directly:
#lang lazy
(define (and a b) (if a b #f))
or in Haskell:
and a b = if a then b else False
and it would have the correct behavior, as a normal function. You would be able to pass this and to a fold, and it would even stop evaluating the list as soon as it encountered a False! Take a look:
Prelude> foldl and True [True, False, error "fail"]
False
(error in Haskell errors out just like 1/0. Since Haskell is statically typed, the arguments to and have to be booleans so you can't use 1/0 directly.)
Like most languages, Scheme's logical AND uses short circuit evaluation, which means its right operand will only be evaluated if the left operand is true. If the left operand is false, then the result of the expression must be false regardless of the value of the right operand, so if the left operand evaluates to false, it returns false immediately, without evaluating the right operand at all.
To be precise, here's the language from the spec (I'm section 4.2.1 of R5RS, but this isn't an area that's likely to change must between revisions of the spec):
(and <test1> ... )
The <test> expressions are evaluated from left to right, and the value of the first expression that evaluates to a false value (see section 6.3.1) is returned. Any remaining expressions are not evaluated.
Boolean shortcutting. The first argument to "and" evaluates to false, therefore the result must be false, and there's no reason for it to evaluate the second argument (and therefore incur the error).

Variable in a function

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.

Resources