Wrong argument number to recur function - recursion

I'm a beginner with functional programming and I try to pretty print a maze.
Here is my function
(defn pprint-maze
[arr row col]
(loop [coll arr idx 0]
(match [idx]
[(_ :guard #(= (mod idx col) 0))] (println "") ; write a \n
:else (print "-")) ; write a wall
(when (next coll)
(recur (next coll) (inc idx)))))
My function takes the collection and the size of the maze and for now, just print a dash and a \n at the end of the row.
The problem I've it's :
Exception in thread "main" clojure.lang.ArityException: Wrong number of args (1) passed to: core/pprint-maze/fn--4873/fn--4874
I think the function pointed out is my loop function, and the problem is related to match (because when I comment the match block, everything work). I think that match try to call the loop function with nil as argument (the return of the println function).
How to solve that ?

The function passed to :guard should take exactly one argument, the value being guarded. Your function takes zero arguments.

Related

How does this count-even racket function work?

I am trying to understand how the count-even function given in my textbook works and I'm not sure if I completely understand it.
I have provided my understanding of the function in comments next to code. Can someone explain what is happening and correct me in each step of this function.
And I don't understand how this function is recursive. What is the base case ?
(define (ce x) ; x is an argument that takes in a list
(if (pair? x) ; I don't understand why this is here
(+ (ce (car x)) ; Add the resuls of recursive call together (0 or 1)
(ce (cdr x)))
(if (and (number? x) (even? x)) ; if x is a number and x is even then return 1 ? Else return 0 ?
1
0) ) )
In a recursive function there are usually two cases:
The result is a call to the same function
The result is a simple value, the base case
You choose between the two cases with an if.
Hence the base case is:
(if (and (number? x) (even? x))
1
0) ) )
And the recursive case is:
(+ (count-evens (car x))
(count-evens (cdr x)))
Comments:
The argument x doesn't need to be a list. pairs? tests for a list. If it is just a value then we have the base case. If an even number then result is one, else zero.
If the argument x is a list, we split it into two parts, the head (car) and the tail (cdr). The head is just a value, and so when we rerun count-evens on it we end up with the base case.
The tail is passed to count-evens which keeps slicing off a value at a time until we have a value in the car and empty list in cdr. In the base case, the first value is assessed for an even number, and the empty list is always evaluated as zero.

Creating a function which takes any number of functions as arguments

I'm having trouble figuring out how to go about creating a function that can take a series of the same function as arguments with the last argument as an operand. For example:
(func sqrt sqrt sqrt 390625)
The call above should return 5 as (sqrt 390625) > (sqrt 625) > (sqrt 25) > 5
I'm having trouble figuring out the exact way I should write this as any way I have tried has given me errors or achieved an infinite loop.
This the code is have so far:
(define func
(lambda L
(cond ( (equal? (length L) 2) ((car L) (cadr L)) ) ;; If the list consists of only 2 elements, carry out the function (element 1) onto the operand (element 2)
( #t (apply (car L) (func (cdr L))) ) ;; otherwise, apply the function (1st element) onto the rest of the list
)
)
)
The first condition works, for example returning 5 if i call (func sqrt 25), however the recursive call is throwing errors.
I would appreciate any help with this.
The OP doesn't provide a definition for chain, so that part is unclear, but I think that a fundamental problem here is that there is no recursive call to func; further, apply isn't used in the right position.
Instead of using (equal (length L) 2) as a base case, it might be nicer to make recursive calls as long as the first element in the input is a procedure, or otherwise just return the element:
#lang racket
(define multi-call
(lambda args
(let ((arg (car args)))
(if (procedure? arg)
(arg (apply multi-call (cdr args)))
arg))))
Here, when arg is a procedure, then it is applied to the result of calling multi-call recursively on the remaining arguments. Note that multi-call takes an arbitrary number of arguments, wrapping them in the list args. The reduction step provides (cdr args), which is a list of the remaining arguments. This means that apply should be used to call multi-call on those remaining arguments because multi-call expects an arbitrary number of arguments, not a list of arguments.
multi-call.rkt> (multi-call sqrt sqrt sqrt 390625)
5

LISP Recursive Triangle

My recursive call seems to not be working, I am trying to make a triangle given an integer, and with the help of you guys I was finally able to make the string print on the same line, the correct amount of times for 1 line. At the end of printing the line, I have a recursive call that calls on triangle to make another line, one character shorter. This call seems to never be reached for some reason. Please find the code below, thank you all in advance for any and all help, it is all greatly appreciated!
Note: On a side note, is there any way to stop a function in Lisp similar to a return statement? I would like for the recursion to stop at k = 1, and not continue to k = 0.
(defun newTriangle (k)
(cond ((<= k 0) (princ '(Nope)))
((or (= k 1) (= k -1)) (princ 'a))
((> k 0) (make-string k :initial-element #\a))
(newTriangle (- k 1))))
(print (newTriangle 3))
sample output triangle(3)
aaa
aa
a
sample output triangle(-3)
aaa
aa
a
First, you need to decide exactly what it is that newTriangle is doing. The call (print (newTriangle 3)) suggests that newTriangle should return a string, which is then printed by the call to print. But, the OP definition of newTriangle is both printing output, and returning a single line of the triangle as a string.
The recursive call to newTriangle is never reached because all possible cases for the value of k are exhausted before this line is reached. Since k can only be less than zero, equal to zero, or greater than zero, and since all of these cases are tested for before reaching the recursive call, it is never reached. Also note that the OP code has the syntax wrong for the final part of the cond statement. The first expression in a cond branch is a test, and the convention is to use t here for a branch that will always be evaluated if reached. But, this many cases are not needed here.
Assuming the newTriangle function should not return a string, but should print a triangle as a side-effect, what should it do? If the input number is greater than 0, it should print a line with a number of characters equal to the input number and then call itself with the input reduced by one; otherwise it should do nothing:
(defun print-triangle (k)
(when (> k 0)
(princ (make-string k :initial-element #\a))
(terpri)
(print-triangle (- k 1))))
This definition is named print-triangle to emphasize that it prints a triangle as a side-effect, and because kebab-case is idiomatic in Lisps, and camelCase is not. Note that each time that print-triangle is called with input greater than zero, a string of the correct length is printed, and then a newline is printed (with the obscurely-named terpri, which just writes a newline to the current output stream), before calling print-triangle again with k reduced by 1.
Sample REPL interaction:
CL-USER> (print-triangle 3)
aaa
aa
a
NIL
If the goal is instead to return a string, one approach would be to call a helper function that keeps the result in a parameter:
(defun new-triangle (k)
(build-triangle k ""))
(defun build-triangle (k result)
(if (> k 0)
(build-triangle (- k 1)
(concatenate 'string
result
(make-string k :initial-element #\a)
(string #\newline)))
result))
Here, new-triangle takes an integer argument, and calls build-triangle, passing both the integer argument and an empty string in the result position. The build-triangle function operates much the same as print-triangle before, but instead of printing the lines, they are concatenated with result, along with a string containing a newline. When build-triangle is finished, the result string is returned to new-triangle. Note that simply calling new-triangle from the REPL will print the resulting string as data (i.e., with quotation marks); calling print on the result of new-triangle will both print the string as data, and return the string. To see the string printed without quotation marks, format can be used; or you could use princ which will print the string without quotation marks, and return the string itself:
CL-USER> (new-triangle 3)
"aaa
aa
a
"
CL-USER> (print (new-triangle 3))
"aaa
aa
a
"
"aaa
aa
a
"
CL-USER> (format t "~A" (new-triangle 3))
aaa
aa
a
NIL
CL-USER> (princ (new-triangle 3))
aaa
aa
a
"aaa
aa
a
"

Variable Not A Number Error in Lisp (Which is not true)

I have a code which takes a list and returns all possible permutations by the parameter result.
But when I compile I have an error which says *** - =: (1+ INDEX) is not a number.
Is this message true or I messed up the code generally?
I am new to lisp I can looking for a fix and also open to suggestions from fucntional programmers.
;; Creates permutatiions of a given list and returns it via parameter
(defun create-permuations (source)
(setf result (list))
(create-permuations-helper source 0 '() result)
result)
(defmacro create-permuations-helper (source index cur result)
(if (= (list-length cur) index)
(cons cur result)
(loop for i from 0 to (list-length cur) do
(create-permuations-helper source (1+ index)
(append cur (list (nth i source))) result))))
99% of times when a compiler reports an error you can trust it to be true. Here Index is the list (1+ index), literally the 1+ symbol followed by the index symbol. This is so because you are using a macro, and macros operate on code.
In your macro, you do not return a form to be evaluated, you execute code during macro-expansion that depends on itself. That alone is an undefined behaviour. For example:
(defmacro a (x)
(if (plusp x)
(a (- x 1))
nil))
In the body of a, you want to expand code using a recursive call to itself. But the macro is not yet fully known and cannot be until the whole macro is defined.
Maybe the particular lisp implementation binds a to the macro function in body of the macro, which is a strange thing to do, or you evaluated the definition twice. The first time the compiler assumes a is an unknown function, then binds a to a macro, and the second time it tries to expand the macro.
Anyway macro are not supposed to be recursive.
In the example, since the macro does not evaluate its argument, the nested call to the macro is given the literal expression (- x 1), and not its actual value, which cannot be known anyway since x is unknown. You are crossing a level of abstraction here by trying to evaluate things at macroexpansion time.
But, macros can expand into code that refers to themselves.
(defmacro a (x)
(if (plusp x)
`(b (a ,(- x 1)))
nil))
Now, (a 2) expands into (b (a 1)), which itself macroexpands into (b (b (a 0))), and finally reaches a fixpoint which is (b (b nil)).
The difference is that the macro produces a piece of code and returns, which the compiler macroexpands again, whereas in the first example, the macro must already be expanded in the body of its own definition.
Possible implementation
One way to solve your problem is to define a local function that has access to a variable defined in your main function. Then, the local function can set it, and you do not need to pass a variable by reference (which is not possible to do):
(defun permut (list)
(let (result)
(labels ((recurse (stack list)
(if list
(dolist (x list)
(recurse (cons x stack)
(remove x list :count 1)))
(push stack result))))
(recurse nil list))
result))
Alternatively, you can split the process in two; first, define permut-helper, which is a higher-order function that takes a callback function; it generates permutations and calls the callback for each one:
(defun permut-helper (stack list callback)
(if list
(dolist (x list)
(permut-helper (cons x stack)
(remove x list :count 1)
callback))
(funcall callback stack)))
You call it with a function that pushes results into a list of permutations:
(defun permut (list)
(let (result)
(flet ((add-result (permutation)
(push permutation result)))
(permut-helper nil list #'add-result))
result))

My code signals the error "application: not a procedure" or "call to non procedure"

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

Resources