Scheme nested lambda function - function

I am a beginner in Scheme. I found this question in MIT exam 1 for SICP lecture.
What's the value and type for –
((lambda (a) (lambda (b) (+ (sqrt a) (sqrt b)))) 5)
I am having a hard time understanding how this function works. I am really confused about the parameter b. Only 5 is passed as a parameter to the outer lambda function, then what value does b take for the inner lambda function?
I tried running this function in mit-scheme but the resulting value gets incremented each time it's run.

You're correct that only the outer lambda form is applied to the argument 5. Then it returns its body with a replaced with 5, so it would return
(lambda (b) (+ (sqrt 5) (sqrt b)))
which is itself a function. This could later be applied to another argument, to produce an actual numeric value.

Related

Equality of Function Designators

Are two Common Lisp function objects with the same symbol designator always eq? For example, this comparison seems to work:
(defun foo (fn)
(let ((ht (make-hash-table)))
(eq (symbol-function (hash-table-test ht)) fn)))
FOO
* (foo #'eql)
T
*(foo #'equal)
NIL
But this may rely on implementations not making latent copies of functions, presumably for reasons of efficiency. Since hash-table-test returns a symbol designator, the other (possibly better) eq alternative would be to derive the symbol from the function object? Is one approach better than the other?
Are two Common Lisp function objects with the same symbol designator always eq?
In Common Lisp a function is a piece of code, be it compiled or not. From the Glossary:
function n. 1. an object representing code, which can be called with zero or more arguments, and which produces zero or more values. 2. an object of type function.
A function designator, on the other hand, can be a symbol:
function designator n. a designator for a function; that is, an object that denotes a function and that is one of: a symbol (denoting the function named by that symbol in the global environment), or a function (denoting itself).
So, a symbol which is a function designator is something that, when evaluated in a certain context, or with a certain syntax like #'symbol or (function symbol), produces a function, and the comparison of two function designators is a comparison of the functions that they denote:
CL-USER> (eql #'car #'cdr)
NIL
CL-USER> (eql #'car (symbol-function 'car))
T
But note that this equality test is just a comparison of the identity of the functional objects (the pieces of code), like in:
CL-USER> (eq #'car #'car)
T
CL-USER> (let ((a (lambda (x) (1+ x))))
(eq a a))
T
but not of the actual bytes that represent them (the code!):
CL-USER> (let ((a (lambda (x) (car x)))
(eq a #'car))
NIL
CL-USER> (defun f (x) (1+ x))
F
CL-USER> (defun g (x) (1+ x))
G
CL-USER> (equalp (function f) (function g))
NIL
CL-USER> (equalp (lambda (x) (1+ x)) (lambda (x) (1+ x)))
NIL
Note that, in all these cases, the two functions compared have not only the same “meaning”, but in most cases the same “source code”, are compiled in the same way, and behaves identically on the same input data. This is because a function is mathematically a (possibly) infinite set of pairs (input, output) and one cannot compare infinte objects.
But this may rely on implementations not making latent copies of functions, presumably for reasons of efficiency.
There is no way for the user to copy a function (neither the system has any reason to perform a copy of a piece of code!), so any function is equal to itself in the same way as any pointer is equal only to itself.
Since hash-table-test returns a symbol designator, the other (possibly better) eq alternative would be to derive the symbol from the function object? Is one approach better than the other?
(I suppose you intend function designator, instead of symbol designator)
Actually, hash-table-test normally returns a function designator only as a symbol, as said in the manual:
test---a function designator. For the four standardized hash table test functions (see make-hash-table), the test value returned is always a symbol. If an implementation permits additional tests, it is implementation-dependent whether such tests are returned as function objects or function names.
So:
CL-USER> (type-of (hash-table-test (make-hash-table)))
SYMBOL
CL-USER> (eq 'eql (hash-table-test (make-hash-table)))
T
CL-USER> (eq #'eql (hash-table-test (make-hash-table)))
NIL
Note that in the last case we are comparing a function (the value of #'eql) with a symbol (what is returned by hash-table-test) and obviously this comparison returns a false value.
In conclusion:
It is not very reasonable to compare functions, unless you want to know if two functions are in effect the same object in memory (for istance if the two things are the same compiled code).
It is always important to distinguish functions from their designations as symbols (function names) or lists, like (LAMBDA parameters body), and decide what we want to actually compare.
#'eql is equivalent to (function eql). Unless there's a lexical function binding of eql, this is defined to return the global function definition of the symbol eql. That's also what (symbol-function 'eql) is defined to return.
So for any globally defined function f that isn't shadowed by a lexical definition,
(eq #'f (symbol-function 'f))
should always be true.

Higher-Order Function Scheme: Incrementing via Returned Value

I'm having issues with some functionality in Scheme
So in this book i'm learning about Scheme i've come across this problem that I don't quite grasp yet.
It's asking me to create a high order function that does this:
(display ((incrementn 4) 2))
6
I've been stuck on this for a couple of hours and still seem to have not understood the fundamentals. So i'm turning to you all in hopes I can get some better understanding on this functional call.
So the way I understand it so far is that when we define a function like so:
(define (increment n) ______)
The blank spaces obviously represent my following manipulation of the arguments given. What i don't seem to understand is how the high order function returns the outside argument (of the increment function) and injects it into the defined function(which is (incrementn 3) )
I understand fully that 3 is the initial value (integer) that we increment n times (n being the argument passed outside of the ((incrementn n) x) ) that we increment n by 1 x times
The question i'm asking you simply is that given x being an unbound variable (right?) how do I return that integer and increment n by 1 that many times? What is the syntax for this kind of behaviour?
The the point to understand here is that after we call incrementn with 3 as the initial argument it will return a function, and that afterwards 2 is passed as an argument to that function. This is called currying, and the solution is straightforward after you grasp the concept at play here:
(define (incrementn n)
(lambda (x)
(+ n x)))
As you can see, the call to incrementn captures the value of the n parameter in the returned lambda, and when we call it passing x, n is there to be used in the expressions in the body of the lambda. Now, it works as expected:
((incrementn 4) 2)
=> 6
((incrementn -1) 3)
=> 2

Tail-Recursive Power Function in Scheme

I am having trouble writing a tail-recursive power function in scheme. I want to write the function using a helper function. I know that I need to have a parameter to hold an accumulated value, but I am stuck after that. My code is as follows.
(define (pow-tr a b)
(define (pow-tr-h result)
(if (= b 0)
result
pow-tr a (- b 1))(* result a)) pow-tr-h 1)
I edited my code, and now it works. It is as follows:
(define (pow-tr2 a b)
(define (pow-tr2-h a b result)
(if (= 0 b)
result
(pow-tr2-h a (- b 1) (* result a))))
(pow-tr2-h a b 1))
Can someone explain to me why the helper function should have the same parameters as the main function. I am having a hard time trying to think of why this is necessary.
It's not correct to state that "the helper function should have the same parameters as the main function". You only need to pass the parameters that are going to change in each iteration - in the example, the exponent and the accumulated result. For instance, this will work fine without passing the base as a parameter:
(define (pow-tr2 a b)
(define (pow-tr2-h b result)
(if (= b 0)
result
(pow-tr2-h (- b 1) (* result a))))
(pow-tr2-h b 1))
It works because the inner, helper procedure can "see" the a parameter defined in the outer, main procedure. And because the base is never going to change, we don't have to pass it around. To read more about this, take a look at the section titled "Internal definitions and block structure" in the wonderful SICP book.
Now that you're using helper procedures, it'd be a good idea to start using named let, a very handy syntax for writing helpers without explicitly coding an inner procedure. The above code is equivalent to this:
(define (pow-tr2 a b)
(let pow-tr2-h [(b b) (result 1)]
(if (= b 0)
result
(pow-tr2-h (- b 1) (* result a)))))
Even though it has the same name, it's not the same parameter. If you dug into what the interpreter is doing you'll see "a" defined twice. Once for the local scope, but it still remembers the "a" on the outer scope. When the interpreter invokes a function it tries to bind the values of the arguments to the formal parameters.
The reason that you pass the values through rather mutating state like you would likely do in an algol family language is that by not mutating state you can use a substitution model to reason about the behaviour of procedures. That same procedure called at anytime with arguments will yeild the same result as it is called from anywhere else with the same arguments.
In a purely functional style values never change, rather you keep calling the function with new values. The compiler should be able to write code in a tight loop that updates the values in place on the stack (tail call elimination). This way you can worry more about the correctness of the algorithm rather than acting as a human compiler, which truth be told is a very inefficient machine-task pairing.
(define (power a b)
(if (zero? b)
1
(* a (power a (- b 1)))))
(display (power 3.5 3))

What is the advantage of a symbol that binds to a value and function at the same time?

In lisp, a symbol can be bound to both a value and a function at the same time.
For example,
Symbol f bound to a function
(defun f(x)
(* 2 x))
Symbol f bound to a value
(setq f 10)
So i write something like this:
(f f)
=> 20
What is the benefit of such a feature?
The symbol can have both a function and a value. The function can be retrieved with SYMBOL-FUNCTION and the value with SYMBOL-VALUE.
This is not the complete view. Common Lisp has (at least) two namespaces, one for functions and one for variables. Global symbols participate in this. But for local functions the symbols are not involved.
So what are the advantages:
no name clashes between identifiers for functions and variables.
Scheme: (define (foo lst) (list lst))
CL: (defun foo (list) (list list))
no runtime checks whether something is really a function
Scheme: (define (foo) (bar))
CL: (defun foo () (bar))
In Scheme it is not clear what BAR is. It could be a number and that would lead to a runtime error when calling FOO.
In CL BAR is either a function or undefined. It can never be anything else. It can for example never be a number. It is not possible to bind a function name to a number, thus this case never needs to be checked at runtime.
It's useful for everyday tasks, but the main reason is because of macros, you'll understand why once you study it.

Mechanism of a function in Scheme

Here it is a strange function in Scheme:
(define f
(call/cc
(lambda (x) x) ) )
(((f 'f) f) 1 )
When f is called in the command line, the result displayed is f .
What is the explanation of this mechanism ?..
Thanks!
You've just stumbled upon 'continuations', possibly the hardest thing of Scheme to understand.
call/cc is an abbreviation for call-with-current-continuation, what the procedure does is it takes a single argument function as its own argument, and calls it with the current 'continuation'.
So what's a continuation? That's infamously hard to explain and you should probably google it to get a better explanation than mine. But a continuation is simply a function of one argument, whose body represents a certain 'continuation' of a value.
Like, when we have (+ 2 (* 2 exp)) with exp being a random expression, if we evaluate that expression there is a 'continuation' waiting for that result, a place where evaluation continues, if it evaluates to 3 for instance, it inserts that value into the expression (* 2 3) and goes on from there with the next 'continuation', or the place where evaluation continues, which is (+ 2 ...).
In almost all contexts of programming languages, the place where computation continues with the value is the same place as it started, though the return statement in many languages is a key counterexample, the continuation is at a totally different place than the return statement itself.
In Scheme, you have direct control over your continuations, you can 'capture' them like done there. What f does is nothing more than evaluate to the current continuation, after all, when (lambda (x) x) is called with the current continuation, it just evaluates to it, so the entire function body does. As I said, continuations are functions themselves whose body can just be seen as the continuation they are to capture, which was famously shown by the designers of Scheme, that continuations are simply just lambda abstractions.
So in the code f first evaluates to the continuation it was called in. Then this continuation as a function is applied to 'f (a symbol). This means that that symbol is brought back to that continuation, where it is evaluated again as a symbol, to reveal the function it is bound to, which again is called with a symbol as its argument, which is finally displayed.
Kind of mind boggling, if you've seen the film 'primer', maybe this explains it:
http://thisdomainisirrelevant.net/1047