I'm not sure what's going wrong here, I believe my syntax is correct but I've no idea what the error is trying to say.
(define (even-nm-inst? n)
(cond ((= n 2) #t)
((= n 4) #t)
((= n 6) #t)
((= n 8) #t)
((= n 10) #t)
((> n 2)
(modulo n 2)
(cond ((= n 0) #t)
(cond ((= n 1) #f)
((< n 2)
(modulo n 2)
(cond ((= n 0) #t)
((= n 1) #f)
)))))))
I'm trying to make a function that determines if a number is even or not.
The specific error returned is:
. ../../Applications/Racket v6.6/share/pkgs/r5rs-lib/r5rs/main.rkt:493:22: with-syntax: binding match failed in: (_ . rest)
Any idea what's going on? I know it's this specific part of code because I have headers on the different sections, and the error appears under the header for this chunk.
Thanks in advance, I'm brand new to scheme.
No, that's not correct – your conds are all over the place, and apparently so much so that Racket is getting confused.
It's not clear at all why you wrote all that code;
(define (even-nm-inst? n)
(= (modulo n 2) 0))
would do, as would using even?.
Well, this is an inexcusably bad syntax error...
but on the other hand, it looks like you're using the extremely-legacy R5RS language. If that's because you're in a class and your instructor requires it, then you're stuck with it. If not, though, you should definitely switch ASAP to the main Racket language, or the Beginning Student language; neither of them should give you that terrible message.
Specifically, in the Beginning Student language, you'll get this message:
"cond: expected a clause with a question and an answer, but found a clause with 3 parts" ... and it highlights the three parts of the clause that are the problem.
Since you are using DrRacket why don't you press CTRL+i and it will format the code according to what you have written and not what you would like to have written. THe result is:
(define (even-nm-inst? n)
(cond ((= n 2) #t)
((= n 4) #t)
((= n 6) #t)
((= n 8) #t)
((= n 10) #t)
((> n 2)
(modulo n 2) ; doesn't do anything since result not used
(cond ((= n 0) #t)
(cond ((= n 1) #f) ; cond doesn't exist as a variable
((< n 2)
(modulo n 2)
(cond ((= n 0) #t) ; cond doesn't exist as a variable
((= n 1) #f)
)))))))
Now. If using even? is not an option I would have written this:
(define (my-even? n)
(cond ((negative? n) (my-even? (- n)))
((zero? n) #t)
((= n 1) #f)
(else (my-even? (- n 2)))))
(my-even? -5) ; ==> #f
(my-even? 10) ; ==> #t
You use modulo and it can be used to produce a result without any conditionals:
(define (my-even? n)
(= 0 (modulo n 2)))
Related
I was reading the SICP and encountered with a problem, in chapter 1 there is an example named counting change, I need to write a program in scheme to calculate the possible number of ways to make a change of any given number given half-dollars, quarters, dimes, nickles and pennies.
the book shows a substitution model of program and I tried to change it to a nesting one but failed, could anyone give me a favor?
(define (count_change total_amount)
(define (denomination kinds_of_coins)
(cond ((= kinds_of_coins 5) 50)
((= kinds_of_coins 4) 25)
((= kinds_of_coins 3) 10)
((= kinds_of_coins 2) 5)
((= kinds_of_coins 1) 1)))
(define (cc amount kinds_of_coins)
(cond (= amount 0) 1)
((or (< amount 0) (= kinds_of_coins 0)) 0)
(else (+ (cc amount (- kinds_of_coins 1))
(cc (- amount (denomination kinds_of_coins)) kinds_of_coins))))
(cc total_amount 5))
the execution result is as follows:
;Ill-formed clause: 1
A cond expression generally takes the form (cond (predicate expr) ... (else expr)) or (cond (predicate expr) ... (#t expr)). Whenever a predicate evaluates to true, the correspondent expression in the clause is the result of the conditional expression. If you do not have an else/#t predicate at the end and all of the predicates on the conditional expression are false, generally the expression returns a void value.
Here, you have a syntax error because you did not started a clause properly. So, instead of having (cond (= amount 0) 1) you should have (cond ((= amount 0) 1) ...).
I'm using Scheme with the full Swindle package, and I'm trying to use conditionals to recursively determine evenness/oddity of integers. My code is as follows:
(define (odd? x)(
(cond
((= x 0) '#f)
((= x 1) '#t)
((= (even? (- x 1)) #t) '#f)
(else '#t))))
(define (even? x)(
(cond
((= x 0) '#f)
((= x 2) '#t)
((= (odd? (- x 1)) #t) '#f)
(else '#t))))
However, when I run (even? x) or (odd? x) [x is some number, doesn't matter what, as I get the same error] I get: application: not a procedure;
expected a procedure that can be applied to arguments
given: #t
arguments...: [none]
Can anyone help? Thanks. I'm not 100% familiar with ideal Scheme syntax, so it might be that.
You have an erroneous pair of parentheses surrounding the cond expression (that's causing the error reported). But also, there are way too many conditions in each procedure, and because you're using = to compare numbers with boolean values, there will be a point where a contract violation will occur. For fixing that you can replace = with equal? in here:
((equal? (even? (- x 1)) #t) '#f)
And in here:
((equal? (odd? (- x 1)) #t) '#f)
But then, the procedures will still give an incorrect result:
(even? 5)
=> #t
(odd? 7)
=> #f
Honestly, I think it'd better to simplify the implementation, that will solve all the problems. Try this instead:
(define (odd? x)
(cond ((= x 0) #f)
(else (even? (- x 1)))))
(define (even? x)
(cond ((= x 0) #t)
(else (odd? (- x 1)))))
Now we'll get correct answers:
(even? 4)
=> #t
(even? 5)
=> #f
(odd? 6)
=> #f
(odd? 7)
=> #t
Any Scheme form in parentheses is an application, like (sin 42) or (42 sin). The first calls sin as a function with argument 42 and produces a value; the second tries to call 42 with an argument sin, but 42 is no procedure, so this causes an error. Similarly (42) is an application with no arguments; still it must have a procedure to be applied as its first part, to be called with no arguments, right? In Scheme, parentheses matter, they are not just for grouping stuff (as they may be in some other languages). So the extra parentheses cause an extra attempt to evaluate the result, which is a Boolean, i.e. not a procedure, so this is an error.
Then, '#f is just #f; similarly for #t (they both evaluate to themselves); and a condition (= test #t)1 (equal? test #t) is the same as just test (produces the same set of Boolean results) ((1 we can't use = to compare Booleans, it is supposed to be used with numbers only)):
(define (odd? x)
(cond
((= x 0) #f)
((= x 1) #t)
((even? (- x 1)) #f)
(else #t)))
Also, (if test #f else...) is the same as (if (not test) else... #f):
(define (odd? x)
(cond
((= x 0) #f)
((= x 1) #t)
((not (even? (- x 1))) #t)
(else #f))) ; (else ...) is like (#t ...)
using logical connectives, the clauses with the same outcome can be merged, and mutually exclusive clauses can be rearranged (mutual exclusivity can be achieved with explicit guards):
(define (odd? x)
(cond
((and (/= x 0) ; a guard
(or (= x 1)
(not (even? (- x 1))))) #t)
((or (= x 0) #t) #f)))
but (cond (test #t) (else #f) is (if test #t #f) which is just test:
(define (odd? x) (and (> x 0) ; `>` is better
(or (= x 1)
(not (even? (- x 1))))))
The guard (> x 0) prevents the fall-through for negative xes.
But then, this is completely wrong. For n to be odd, n-1 must be even, not the opposite!
(define (odd? x) (and (> x 0) ; work only for positive integers
(or (= x 1)
(even? (- x 1)))))
We could write (not (odd? (- x 1))), but then it wouldn't be tail recursive. It would be tail recursive modulo cons (not serving as a "constructor"), but for some historic fluke of a reason2, TRMC optimization isn't required of a Scheme implementation. The last expression in and and or forms is, in fact, in tail position. But not in not. ((2 despite being described as early as 1974.))
Repeat the same for your definition of even?.
I have written a simple procedure to find the divisors of a number (not including the number itself). I have figured out how to print them, but I would like to have this function return a list containing each of the divisors.
(define (divisors n)
(do ((i 1 (+ i 1)))
((> i (floor (/ n 2))))
(cond
((= (modulo n i) 0)
(printf "~a " i)))))
My idea is to create a local list, adding elements to it where my printf expression is, and then having the function return that list. How might I go about doing that? I am new to Scheme, and Lisp in general.
Do you necessarily have to use have to use do? here's a way:
(define (divisors n)
(do ((i 1 (add1 i))
(acc '() (if (zero? (modulo n i)) (cons i acc) acc)))
((> i (floor (/ n 2)))
(reverse acc))))
But I believe it's easier to understand if you build an output list with a named let:
(define (divisors n)
(let loop ((i 1))
(cond ((> i (floor (/ n 2))) '())
((zero? (modulo n i))
(cons i (loop (add1 i))))
(else (loop (add1 i))))))
Or if you happen to be using Racket, you can use for/fold like this:
(define (divisors n)
(reverse
(for/fold ([acc '()])
([i (in-range 1 (add1 (floor (/ n 2))))])
(if (zero? (modulo n i))
(cons i acc)
acc))))
Notice that all of the above solutions are written in a functional programming style, which is the idiomatic way to program in Scheme - without using mutation operations. It's also possible to write a procedural style solution (see #GoZoner's answer), similar to how you'd solve this problem in a C-like language, but that's not idiomatic.
Just create a local variable l and extend it instead of printing stuff. When done, return it. Like this:
(define (divisors n)
(let ((l '()))
(do ((i 1 (+ i 1)))
((> i (floor (/ n 2))))
(cond ((= (modulo n i) 0)
(set! l (cons i l))))
l))
Note that because each i was 'consed' onto the front of l, the ordering in l will be high to low. Use (reverse l) as the return value if low to high ordering is needed.
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input).
(define (isPrimeHelper x k)
(if (= x k) #t
(if (= (remainder x k) 0) #f
(isPrimeHelper x (+ k 1)))))
(define ( isPrime x )
(cond
(( = x 1 ) #t)
(( = x 2 ) #t)
( else (isPrimeHelper x 2 ) )))
(define (printPrimesUpTo n)
(define result '())
(define (helper x)
(if (= x (+ 1 n)) result
(if (isPrime x) (cons x result) ))
( helper (+ x 1)))
( helper 1 ))
My check for prime works, however the function printPrimesUpTo seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list.
Thanks :)
You have several things wrong, and your code is very non-idiomatic. First, the number 1 is not prime; in fact, is it neither prime nor composite. Second, the result variable isn't doing what you think it is. Third, your use of if is incorrect everywhere it appears; if is an expression, not a statement as in some other programming languages. And, as a matter of style, closing parentheses are stacked at the end of the line, and don't occupy a line of their own. You need to talk with your professor or teaching assistant to clear up some basic misconceptions about Scheme.
The best algorithm to find the primes less than n is the Sieve of Eratosthenes, invented about twenty-two centuries ago by a Greek mathematician who invented the leap day and a system of latitude and longitude, accurately measured the circumference of the Earth and the distance from Earth to Sun, and was chief librarian of Ptolemy's library at Alexandria. Here is a simple version of his algorithm:
(define (primes n)
(let ((bits (make-vector (+ n 1) #t)))
(let loop ((p 2) (ps '()))
(cond ((< n p) (reverse ps))
((vector-ref bits p)
(do ((i (+ p p) (+ i p))) ((< n i))
(vector-set! bits i #f))
(loop (+ p 1) (cons p ps)))
(else (loop (+ p 1) ps))))))
Called as (primes 50), that returns the list (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47). It is much faster than testing numbers for primality by trial division, as you are attempting to do. If you must, here is a proper primality checker:
(define (prime? n)
(let loop ((d 2))
(cond ((< n (* d d)) #t)
((zero? (modulo n d)) #f)
(else (loop (+ d 1))))))
Improvements are possible for both algorithms. If you are interested, I modestly recommend this essay on my blog.
First, it is good style to express nested structure by indentation, so it is visually apparent; and also to put each of if's clauses, the consequent and the alternative, on its own line:
(define (isPrimeHelper x k)
(if (= x k)
#t ; consequent
(if (= (remainder x k) 0) ; alternative
;; ^^ indentation
#f ; consequent
(isPrimeHelper x (+ k 1))))) ; alternative
(define (printPrimesUpTo n)
(define result '())
(define (helper x)
(if (= x (+ 1 n))
result ; consequent
(if (isPrime x) ; alternative
(cons x result) )) ; no alternative!
;; ^^ indentation
( helper (+ x 1)))
( helper 1 ))
Now it is plainly seen that the last thing that your helper function does is to call itself with an incremented x value, always. There's no stopping conditions, i.e. this is an infinite loop.
Another thing is, calling (cons x result) does not alter result's value in any way. For that, you need to set it, like so: (set! result (cons x result)). You also need to put this expression in a begin group, as it is evaluated not for its value, but for its side-effect:
(define (helper x)
(if (= x (+ 1 n))
result
(begin
(if (isPrime x)
(set! result (cons x result)) ) ; no alternative!
(helper (+ x 1)) )))
Usually, the explicit use of set! is considered bad style. One standard way to express loops is as tail-recursive code using named let, usually with the canonical name "loop" (but it can be any name whatever):
(define (primesUpTo n)
(let loop ((x n)
(result '()))
(cond
((<= x 1) result) ; return the result
((isPrime x)
(loop (- x 1) (cons x result))) ; alter the result being built
(else (loop (- x 1) result))))) ; go on with the same result
which, in presence of tail-call optimization, is actually equivalent to the previous version.
The (if) expression in your (helper) function is not the tail expression of the function, and so is not returned, but control will always continue to (helper (+ x 1)) and recurse.
The more efficient prime?(from Sedgewick's "Algorithms"):
(define (prime? n)
(define (F n i) "helper"
(cond ((< n (* i i)) #t)
((zero? (remainder n i)) #f)
(else
(F n (+ i 1)))))
"primality test"
(cond ((< n 2) #f)
(else
(F n 2))))
You can do this much more nicely. I reformated your code:
(define (prime? x)
(define (prime-helper x k)
(cond ((= x k) #t)
((= (remainder x k) 0) #f)
(else
(prime-helper x (+ k 1)))))
(cond ((= x 1) #f)
((= x 2) #t)
(else
(prime-helper x 2))))
(define (primes-up-to n)
(define (helper x)
(cond ((= x 0) '())
((prime? x)
(cons x (helper (- x 1))))
(else
(helper (- x 1)))))
(reverse
(helper n)))
scheme#(guile-user)> (primes-up-to 20)
$1 = (2 3 5 7 11 13 17 19)
Please don’t write Scheme like C or Java – and have a look at these style rules for languages of the lisp-family for the sake of readability: Do not use camel-case, do not put parentheses on own lines, mark predicates with ?, take care of correct indentation, do not put additional whitespace within parentheses.
(define (ispowerof2? n)
(cond ((< n 1) #f)
((= n 1) #t)
((> (remainder n 2) 0) #f)
(else (ispowerof2? (/ n 2)))))
Is this code correct and how to write the same function with tail recursion?
I agree with the other two answers. To explain a bit more deeply: a "tail-recursive" function is one where all recursive calls are in tail position. This begs the question of what constitutes a tail call.
One way to see the tail calls is to run this function using DrRacket's stepper. In particular, set the langage level to "Beginning Student" and click the "step" button on this program:
(define (ispowerof2? n)
(cond
((< n 1) false)
((= n 1) true)
((> (remainder n 2) 0) false)
(else (ispowerof2? (/ n 2)))))
(ispowerof2? 36)
... then step forward until you get to a recursive call:
(define (ispowerof2? n)
(cond
((< n 1) false)
((= n 1) true)
((> (remainder n 2) 0) false)
(else (ispowerof2? (/ n 2)))))
(ispowerof2? (/ 36 2))
Note that the recursive call is at the top level; there's no "context" wrapping it, with code to be applied to the result of the call. This is what is meant by a "tail call". Contrast this with a function that computes the length of a list:
(define (len l)
(cond
((empty? l) 0)
(else (+ 1 (len (rest l))))))
(len (cons 3 (cons 4 empty))
Step forward until you get a recursive call, and you'll see this:
(define (len l)
(cond
((empty? l) 0)
(else (+ 1 (len (rest l))))))
(+ 1 (len (list 4)))
See how the recursive call to 'len' is inside of a (+ 1 ...) expression? That's because this call is not in tail position; there are still more expressions to evaluate in this function after the return of the recursive call.
Not quite. The line:
(else (ispower2? (/ n 2)))))
Contains an error - it should be ispowerof2. Otherwise, this is tail recursion.
Yes, this is tail recursive. :)