Trying to write a function that returns another function, but Racket says my lambda is not a function definition? - scheme

Programming in racket, I am trying to write a function that takes a single integer, and returns a function that increments that integer by another integer. For example:
((incnth 5) 3) --> 8
((incnth 3) -1) --> 2
Unfortunately I don't seem to understand lambda functions still, because my code keeps saying that my lambda is not a function definition. Here is what I wrote.
(define (incnth n)
(lambda (f) (lambda (x) (+ n x))))

You have one more lambda than it's needed. If I understand correctly, the idea is to have a procedure that creates procedures that increment a number with a given number. So you should do this:
(define (incnth n) ; this is a procedure
(lambda (x) (+ n x))) ; that returns a lambda
The returned lambda will "remember" the n value:
(define inc2 (incnth 2))
And the resulting procedure can be used as usual, with the expected results:
(inc2 40)
=> 42
((incnth 5) 3)
=> 8
((incnth 3) -1)
=> 2

Related

Scheme define a lambda

I have the following function to compute the sum from A to B of a function in scheme:
(define (SUM summation-function A increment-function B)
(if (> A B)
0
(+ (summation-function A)
(SUM
summation-function (increment-function A) increment-function B))))
Currently I define two procedures before calling the function, for example:
(define (self x) x) ; do nothing, just sum itself
(define (inc x) (+ x 1)); normal +1 increment
(SUM self 0 inc 5)
How instead could I just define the procedure in the call itself, for example:
; in pseudocode
(SUM, lambda x: x, 0, lambda x: (+ x 1), 5)
You can rewrite your definitions like this:
(define self
(lambda (x)
x))
(define inc
(lambda (x)
(+ x 1)))
Now you haves split up creating the variable self and inc and the lambda syntax that creates a closure. It is EXACTLY the same as what you wrote in your question.
By substitution rules you should be able to replace a variable with the expression in its definition:
(SUM self 0 inc 5)
;; is the same as
(SUM (lambda (x)
x)
0
(lambda (x)
(+ x 1))
5)
Please note that older Scheme reports wasn't case sensitive, but SUM and sum are two different names in later reports. It is also common to use lower space letters for variables and procedure names are, as I showed earlier, variables. This is why the procedure list stops working when you define a value to the variable list. One namespace to rule them all.
Typically, we'd use lambdas like this:
(SUM (lambda (x) x) 0 (lambda (x) (+ x 1)) 5)
For the above example in particular, some Scheme interpreters already provide built-in procedures that do precisely what you want and we can simply say:
(SUM identity 0 add1 5)

application: not a procedure drracket scheme [duplicate]

During the execution of my code I get the following errors in the different Scheme implementations:
Racket:
application: not a procedure;
expected a procedure that can be applied to arguments
given: '(1 2 3)
arguments...:
Ikarus:
Unhandled exception
Condition components:
1. &assertion
2. &who: apply
3. &message: "not a procedure"
4. &irritants: ((1 2 3))
Chicken:
Error: call of non-procedure: (1 2 3)
Gambit:
*** ERROR IN (console)#2.1 -- Operator is not a PROCEDURE
((1 2 3) 4)
MIT Scheme:
;The object (1 2 3) is not applicable.
;To continue, call RESTART with an option number:
; (RESTART 2) => Specify a procedure to use in its place.
; (RESTART 1) => Return to read-eval-print level 1.
Chez Scheme:
Exception: attempt to apply non-procedure (1 2 3)
Type (debug) to enter the debugger.
Guile:
ERROR: In procedure (1 2 3):
ERROR: Wrong type to apply: (1 2 3)
Chibi:
ERROR in final-resumer: non procedure application: (1 2 3)
Why is it happening
Scheme procedure/function calls look like this:
(operator operand ...)
Both operator and operands can be variables like test, and + that evaluates to different values. For a procedure call to work it has to be a procedure. From the error message it seems likely that test is not a procedure but the list (1 2 3).
All parts of a form can also be expressions so something like ((proc1 4) 5) is valid syntax and it is expected that the call (proc1 4) returns a procedure that is then called with 5 as it's sole argument.
Common mistakes that produces these errors.
Trying to group expressions or create a block
(if (< a b)
((proc1)
(proc2))
#f)
When the predicate/test is true Scheme assumes will try to evaluate both (proc1) and (proc2) then it will call the result of (proc1) because of the parentheses. To create a block in Scheme you use begin:
(if (< a b)
(begin
(proc1)
(proc2))
#f)
In this (proc1) is called just for effect and the result of teh form will be the result of the last expression (proc2).
Shadowing procedures
(define (test list)
(list (cdr list) (car list)))
Here the parameter is called list which makes the procedure list unavailable for the duration of the call. One variable can only be either a procedure or a different value in Scheme and the closest binding is the one that you get in both operator and operand position. This would be a typical mistake made by common-lispers since in CL they can use list as an argument without messing with the function list.
wrapping variables in cond
(define test #t) ; this might be result of a procedure
(cond
((< 5 4) result1)
((test) result2)
(else result3))
While besides the predicate expression (< 5 4) (test) looks correct since it is a value that is checked for thurthness it has more in common with the else term and whould be written like this:
(cond
((< 5 4) result1)
(test result2)
(else result3))
A procedure that should return a procedure doesn't always
Since Scheme doesn't enforce return type your procedure can return a procedure in one situation and a non procedure value in another.
(define (test v)
(if (> v 4)
(lambda (g) (* v g))
'(1 2 3)))
((test 5) 10) ; ==> 50
((test 4) 10) ; ERROR! application: not a procedure
Undefined values like #<void>, #!void, #<undef>, and #<unspecified>
These are usually values returned by mutating forms like set!, set-car!, set-cdr!, define.
(define (test x)
((set! f x) 5))
(test (lambda (x) (* x x)))
The result of this code is undetermined since set! can return any value and I know some scheme implementations like MIT Scheme actually return the bound value or the original value and the result would be 25 or 10, but in many implementations you get a constant value like #<void> and since it is not a procedure you get the same error. Relying on one implementations method of using under specification makes gives you non portable code.
Passing arguments in wrong order
Imagine you have a fucntion like this:
(define (double v f)
(f (f v)))
(double 10 (lambda (v) (* v v))) ; ==> 10000
If you by error swapped the arguments:
(double (lambda (v) (* v v)) 10) ; ERROR: 10 is not a procedure
In higher order functions such as fold and map not passing the arguments in the correct order will produce a similar error.
Trying to apply as in Algol derived languages
In algol languages, like JavaScript and C++, when trying to apply fun with argument arg it looks like:
fun(arg)
This gets interpreted as two separate expressions in Scheme:
fun ; ==> valuates to a procedure object
(arg) ; ==> call arg with no arguments
The correct way to apply fun with arg as argument is:
(fun arg)
Superfluous parentheses
This is the general "catch all" other errors. Code like ((+ 4 5)) will not work in Scheme since each set of parentheses in this expression is a procedure call. You simply cannot add as many as you like and thus you need to keep it (+ 4 5).
Why allow these errors to happen?
Expressions in operator position and allow to call variables as library functions gives expressive powers to the language. These are features you will love having when you have become used to it.
Here is an example of abs:
(define (abs x)
((if (< x 0) - values) x))
This switched between doing (- x) and (values x) (identity that returns its argument) and as you can see it calls the result of an expression. Here is an example of copy-list using cps:
(define (copy-list lst)
(define (helper lst k)
(if (null? lst)
(k '())
(helper (cdr lst)
(lambda (res) (k (cons (car lst) res))))))
(helper lst values))
Notice that k is a variable that we pass a function and that it is called as a function. If we passed anything else than a fucntion there you would get the same error.
Is this unique to Scheme?
Not at all. All languages with one namespace that can pass functions as arguments will have similar challenges. Below is some JavaScript code with similar issues:
function double (f, v) {
return f(f(v));
}
double(v => v * v, 10); // ==> 10000
double(10, v => v * v);
; TypeError: f is not a function
; at double (repl:2:10)
// similar to having extra parentheses
function test (v) {
return v;
}
test(5)(6); // == TypeError: test(...) is not a function
// But it works if it's designed to return a function:
function test2 (v) {
return v2 => v2 + v;
}
test2(5)(6); // ==> 11

Why does make-counter procedure contains two lambda definition?

I'm trying to understand the scheme code of make-counter procedure. It's a higher order procedure (a procedure outputs another procedure) and I'm stuck with it.
(define make-counter
(lambda (n)
(lambda ()
(set! n (+ n 1))
n)))
(define ca (make-counter 0))
(ca)
(ca)
This outputs 1 and 2 respectively as expected. Why do we need 2 nested procedures here? What are their functions individually?
I'd be appreciated if someone explains in details. Thanks from now on.
Indented properly, this is:
(define make-counter
(lambda (n)
(lambda ()
(set! n (+ n 1))
n)))
By the way, you can use a different syntax:
(define (make-counter n)
(lambda ()
(set! n (+ n 1))
n))
make-counter is a function that accepts a number n and returns an object called closure, which acts like a function but contains a state. Different invocations of make-counter will produce different closures, even when given the same n in argument. A closure can be called using the function-call syntax, as you experimented.
When you call the closure, the code that is contained within is executed. In your example, the closure accepts zero arguments, and mutates the variable named n. Again, the binding from n to a value is local to the closure and different for all instances of counters. But inside a particular counter, n always refer to the same memory location.
A call to the set! function changes what n evaluates to, and replaces the previous value with (+ n 1), incrementing the local counter variable.

How does a closure occur in this scheme snippet?

I'm having some trouble deciphering this code snippet.
(define (stream n f)
(define (next m)
(cons m (lambda () (next (f m)))))
(next n))
(define even (stream 0 (lambda (n) (+ n 2))))
I understand that 'even' is defined as a variable using the 'stream' function, which contains parameters 0 and '(lambda (n) (+ n 2))'. Inside of 'stream', wouldn't '(next n)' indefinitely create cons nodes with a car of n + 2? Yet when I return 'even', it is a cons of (0 . # < Closure>). Could someone be so kind as to explain why this is? Thanks!
Everytime (lambda ...) is evaluated it becomes a closure. What it means is that f is free and available for both procedures next and for the anonymous procedure it creates. m, which is a bound variable in next is also captured as a free variable in the anonymous procedure. If the language were dynamically bound none of them would exist if you called the resulting procedure in the cdr since the bindings would no longer exist, but since we have closures the variable exists even after the procedures that created them ended.
The pair returned by the stream procedure has references to the closure created when (lambda (n) (+ n 2)) was evaluated though the name f even though the call is finished. Thus if you do:
((cdr even)) ; ==>
(#<closure>) ; ==>
(cons 2 #<new-closure>) ; ==> Here
It's important to know that the evaluation of next becomes a pair with a new closure that has a new free variable m that is 2 this time. For each time you call the cdr it creates a new pair with a new closure. If it was the same each time you wouldn't have different result each iteration.
A lambda on it's own doesn't run the code in it's body. Thus instead of infinite recursion you only get one step and the result (cons 2 #<new-closure>). You need to call the cdr of this again ni order to get one more step. etc. Likewise if I did this:
(define (test a)
(define (helper b)
(+ a b))
helper) ; return the helper that has a as closure variable
Since we actually don't use the name one could just have anonymous lambda there instead of the define + the resulting variable. Anyway, you get something that gives you partially application:
((test 5) 2) ; ==> 7
(define ten-adder (test 10))
(ten-adder 2) ; ==> 12
(ten-adder 5) ; ==> 15

trying to understand church encoding in Scheme

I'm trying to understand the whole principal of church encoding through Scheme. I think I understand the basics of it such as
Church numeral for 0
(define c-0
(lambda (f)
(lambda (x)
x)))
Church numeral for 1
(define c-1
(lambda (f)
(lambda (x)
(f x))))
... and continue applying the function to x N times.
Now my problem is just what does this all mean? If I take church-3 for example:
(define c-3
(lambda (x)
(lambda (f)
(f (f (f x))))))
What is this actually doing? I have only basic scheme knowledge as well but I don't even understand how to use the function? what is an example input using the c-3 function? is it just applying something 3 times like a loop?
You are right. c-3 in this case is a function, that takes 1 argument. And returns another function.
This other function takes a 1 argument function, and applies it to the first argument.
In this example, I'm calling c-3 with an argument of 3, this will return a function.
Then, I feed this function, another function, that add1 to x.
((c-3 3) (lambda (x) (add1 x)))
6
This will produce 6 as you see. It applies add1 to 3, 3 times. I know this is confusing. But you can
manually replace the arguments in the body of the function to understand it better. Wherever you see f, just replace that with (lambda (x) (add1 x)) And replace x with 3 (or any number).
This will work with any 1 argument function as long as the argument is of the correct type.

Resources