Keep getting procedure application: expected procedure, from this code - scheme

Im learning Scheme currently and have been tasked with writing something to count the length of a list, this is the code i currently have.
{define (len x)
(if(not(null? x))
(+ 1 len(cdr x))
(0))}
when run with '(2 3 4 5) it gives:
procedure application: expected procedure, given: '(2 3 4 5) (no arguments)
as an error. What am I doing wrong?

You have parentheses problems. Try this:
(define (len x)
(if (not (null? x))
(+ 1 (len (cdr x)))
0))
In particular, notice that:
When you're going to call a function, the function name (and the parameters, if any) must be surrounded by (). So len(x) is wrong, and (len x) is right
If something is not a function, then don't surround it with (). If you write (0), Scheme believes that 0 is a function and tries to apply it, which clearly is going to fail

Related

What is supposed to happen when a procedure's argument is given multiple values when it expects one value only?

(+ (values 1) (values 2)) returns 3. What is (+ 1 (values 2 3)) supposed to return? In R7RS-small, is the second value in a (values ...) automatically ignored when only one value is needed? In Guile 3.0.7, (+ 1 (values 2 3)) returns 3, but it gives an error in MIT Scheme 11.2 and Chibi 0.10.0.
(+ (values 1) (values 2)) is fine, and the result should be 3. But it is not the case that unneeded values are automatically ignored in a values expression; in fact the behavior of (+ 1 (values 2 3)) is unspecified in both R6RS and R7RS Scheme.
From the entry for values from R6RS 11.15 [emphasis mine]:
Delivers all of its arguments to its continuation....
The continuations of all non-final expressions within a sequence of
expressions, such as in lambda, begin, let, let*, letrec,
letrec*, let-values, let*-values, case, and cond forms,
usually take an arbitrary number of values.
Except for these and the continuations created by call-with-values,
let-values, and let*-values, continuations implicitly accepting a
single value, such as the continuations of <operator> and
<operand>s of procedure calls or the <test> expressions in
conditionals, take exactly one value. The effect of passing an
inappropriate number of values to such a continuation is undefined.
R7RS has similar language in 6.10:
The effect of passing no values or more than one value to continuations that were not created in one of these ways is unspecified.
The reason that (+ (values 1) (values 2)) is ok is that continuations of operands in procedure calls take exactly one value. (values 1) and (values 2) each provide exactly one value for their respective continuations.
call-with-values is meant for connecting producers of multiple values with procedures which consume those values. The first argument to call-with-values should be a procedure which takes no arguments and produces values to be consumed. The second argument should be a procedure which accepts the number of values produced by the first procedure:
> (call-with-values (lambda () (values 2 3))
(lambda (x y) (+ 1 x y)))
6
Note that the above use of call-with-values requires the consumer to accept the number of values produced by the producer since Scheme requires that implementations raise an error when a procedure does not accept the number of arguments passed to it:
> (call-with-values (lambda () (values 2 3 4))
(lambda (x y) (+ 1 x y)))
Exception: incorrect argument count in call (call-with-values (lambda () (values 2 3 4)) (lambda (x y) (+ 1 x y)))
If it is desirable for extra arguments to be ignored, the consumer must be designed towards that goal. Here the consumer is designed to ignore all but its first argument:
> (call-with-values (lambda () (values 2 3 4))
(lambda (x . xs) (+ 1 x)))
3

Scheme higher-order function

I try to create a procedure that converts a binary number in a list to a string. Sample output: (binary->string '(1 1 0 1 0 0)) should give "110100".
(define reduce
(lambda (op base x) ;passing by name
(if (null? x)
base
(op (car x) (reduce op base (cdr x))))))
And here is my code:
(define (binary->string lst)
(reduce (number->string lst list->string )))
I know it is wrong but it is the best I came out with so far. Please help me to make it work properly.
Before I will show you solution, here is some advice: when you write Racket code, you should check correct number of arguments and their type.
In this case, you know that reduce needs (op base x), that are three arguments, but when you use some unknown function, like number->string, there is Racket documentation and after short search, you fill find number->string entry:
(number->string z [radix]) → string?
z : number?
radix : (or/c 2 8 10 16) = 10
Returns a string that is the printed form of z (see Printing Numbers) in the base specified by radix. If z is inexact, radix must be 10, otherwise the exn:fail:contract exception is raised.
Examples:
(number->string 3.0)
"3.0"
(number->string 255 8)
"377"
As you can see, you can call this function with one or two arguments, but in both cases, they have to be number. But with this call (number->string lst list->string ), you are passing list and procedure- so I can already tell that your code will end with error. And when you try to call your function in REPL, exactly this happens:
> (binary->string '(1 0 0 1))
. . number->string: contract violation
expected: number?
given: '(1 0 0 1)
argument position: 1st
other arguments...:
After you carefully check what did you write, you should be able to predict what will happen, before you even run your code.
Here is solution:
(define (binary->string lst)
(reduce string-append "" (map number->string lst)))
You will use map to create string from each number in list, then you join these strings with your reduce and string-append.

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

creating a procedure which takes list as an argument

I am a newbie in scheme and I am trying to write a procedure which always finds a list's tail's first element. This is important in recursive calls.
Here is my procedure :
(define second (lambda (x) (car(cdr(x))))
and this is how i try to check it whether it runs correctly or not:
>(define x (list 1 2 3 4))
>(second x)
and this is the error :
procedure application: expected procedure, given: (1 2 3 4) (no arguments)
=== context ===
stdin::184: second
/usr/share/racket/collects/racket/private/misc.rkt:85:7
What might be the problem? Can you give me an inspiration? Is my definition of "second" wrong or what?
Thanks in advance.
There's an extra, unnecessary pair of parenthesis in your code. This fixes it:
(define second (lambda (x) (car (cdr x))))
To be clear, this was wrong: (cdr(x)). The correct form is: (cdr x). Remember, whenever you need to apply a function f to an argument x the correct way is: (f x).
Scheme uses S-expressions, so instead of car(x), you should use (car x). In your case, that means (car (cdr x)), not car(cdr(x)).

Why doesn't this scheme program work as expected?

(define wadd (lambda (i L)
(if (null? L) 0
(+ i (car L)))
(set! i (+ i (car L)))
(set! L (cdr L))))
(wadd 9 '(1 2 3))
This returns nothing. I expect it to do (3 + (2 + (9 + 1)), which should equate to 15. Am I using set! the wrong way? Can I not call set! within an if condition?
I infer from your code that you intended to somehow traverse the list, but there's nothing in the wadd procedure that iterates over the list - no recursive call, no looping instruction, nothing: just a misused conditional and a couple of set!s that only get executed once. I won't try to fix the procedure in the question, is beyond repair - I'd rather show you the correct way to solve the problem. You want something along these lines:
(define wadd
(lambda (i L)
(let loop ((L L)
(acc i))
(if (null? L)
acc
(loop (cdr L) (+ (car L) acc))))))
When executed, the previous procedure will evaluate this expression: (wadd 9 '(1 2 3)) like this:
(+ 3 (+ 2 (+ 1 9))). Notice that, as pointed by #Maxwell, the above operation can be expressed more concisely using foldl:
(define wadd
(lambda (i L)
(foldl + i L)))
As a general rule, in Scheme you won't use assignments (the set! instruction) as frequently as you would in an imperative, C-like language - a functional-programming style is preferred, which relies heavily on recursion and operations that don't mutate state.
I think that if you fix your indentation, your problems will become more obvious.
The function set! returns <#void> (or something of similar nothingness). Your lambda wadd does the following things:
Check if L is null, and either evaluate to 0 or i + (car L), and then throw away the result.
Modify i and evaluate to nothing
Modify L and return nothing
If you put multiple statements in a lambda, they are wrapped in a begin statement explicitly:
(lambda () 1 2 3) => (lambda () (begin 1 2 3))
In a begin statement of multiple expressions in a sequence, the entire begin evaluates to the last statement's result:
(begin 1 2 3) => 3

Resources