Scheme check value if not even - scheme

I have the following function to check if a positive value is even.
(define (even? n)
(cond
((= n 0) #t)
((< n 0) #f)
(else (even? (- n 2)))
)
)
I am trying to use this function to increment a store counter when a checked value is not even (odd) using both the even? function and a logical not, but I can't seem to figure out the correct syntax.
(define (function a b)
(define (iter a b store)
(cond
((= b 1) (+ store a)
(else
(iter (double a) (halve b) (if (not (even? b)) (+ a store) store)))
)
)
(iter a b 0)
)
Could anyone check my syntax to see what I am doing wrong?
A call of (function 1 1) should return 1
A call of (fucntion 1960 56) should return 109760 but I receive 141120
EDIT:
I realize that my halve funciton must be impromperly defined. I tried to implement a halving function that used only subtraction.
(define (halve n)
(define (iter src store)
(cond
((<= src 0) store)
(else (iter (- src 2) (+ store 1)))
)
)
(iter n 0)
)

Please note that the even? function is built-in, you don't have to implement it. Now regarding the problem - this line is not doing what you think:
(if (not (even? b)) (+ a store))
That expression doesn't update the value of store, it's just evaluating the result of adding a to store and then the value obtained is lost - we didn't save it, we didn't pass it to the recursion, the result of the addition is discarded and then the next line is executed.
In Scheme, we use set! to update a variable, but that's frowned upon, we try to avoid mutation operations - and in this case it's not necessary, we only need to pass the correct value to the recursive call.
UPDATE
Now that you've made it clear that you're implementing the Ethiopian multiplication algorithm, this is how it should be done:
(define (halve n)
(quotient n 2))
(define (double n)
(* 2 n))
(define (function a b)
(define (iter a b store)
(cond
((= a 0) store)
((even? a) (iter (halve a) (double b) store))
(else (iter (halve a) (double b) (+ store b)))))
(iter a b 0))
It works as expected:
(function 1 1)
=> 1
(function 1960 56)
=> 109760

You seem to be missing a ), just before the call to iter.

Related

Scheme quadratic function/square root check

Im want to make a function where rootcheck has a list L as input, L always is 3 atoms (a b c) where a is coefficient of x^2, b coef of x and c is the constant. it checks if the equation is quadratic, using discriminant (b^2 - 4ac) and should output this (num 'L) where num is the number of roots and L is a list that contains the roots themselves (using quadratic formula), L is empty in case of no roots. here is my code:
(define roots-2
(lambda (L)
(let ((d (- (* (cdr L) (cdr L)) (4 (car L) (caddr L))))))
(cond ((< d 0) (cons(0 null)))
((= d 0) (cons(1 null)))
(else((> d 0) (cons(2 null)))))
))
its giving me no expression in body error.
also I tried to code the quadratic function and even tried some that are online, one compiled fint but gave me an error when I inserted input this is the code for the quadratic function, NOT MINE!
(define quadratic-solutions
(lambda (a b c) (list (root1 a b c) (root2 a b c))))
(define root1
(lambda (a b c) (/ (+ (- b) (sqrt (discriminant a b c)))
(* 2 a))))
(define root2
(lambda (a b c) (/ (- (- b) (sqrt (discriminant a b c)))
(*2 a))))
(define discriminant
(lambda (a b c) (- (square b) (* 4 (* a c)))))
There are several mistakes in the code:
Some parentheses are incorrectly placed, use a good IDE to detect such problems. This is causing the error reported, the let doesn't have a body
You forgot to multiply in the 4ac part
You're incorrectly accessing the second element in the list
The else part must not have a condition
The output list is not correctly constructed
This should fix the errors, now replace null with the actual call to the function that calculates the roots for the second and third cases (the (< d 0) case is fine as it is):
(define roots-2
(lambda (L)
(let ((d (- (* (cadr L) (cadr L)) (* 4 (car L) (caddr L)))))
(cond ((< d 0) (list 0 null))
((= d 0) (list 1 null))
(else (list 2 null))))))
for the quadractic function part, I found a code online and tweaked it to provide both roots of a quadratic equation. returns a list of both roots
(define (solve-quadratic-equation a b c)
(define disc (sqrt (- (* b b)
(* 4.0 a c))))
(list (/ (+ (- b) disc) (* 2.0 a))
(/ (- (- b) disc) (* 2.0 a))
))

How to write a simple profiler for Scheme

I would like to write a simple profiler for Scheme that gives a count of the number of times each function in a program is called. I tried to redefine the define command like this (eventually I'll add the other forms of define, but for now I am just trying to write proof-of-concept code):
(define-syntax define
(syntax-rules ()
((define (name args ...) body ...)
(set! name
(lambda (args ...)
(begin
(set! *profile* (cons name *profile*))
body ...))))))
My idea was to record in a list *profile* each call to a function, then later to examine the list and determine function counts. This works, but stores the function itself (that is, the printable representation of the function name, which in Chez Scheme is #<procedure f> for a function named f), but then I can't count or sort or otherwise process the function names.
How can I write a simple profiler for Scheme?
EDIT: Here is my simple profiler (the uniq-c function that counts adjacent duplicates in a list comes from my Standard Prelude):
(define *profile* (list))
(define (reset-profile)
(set! *profile* (list)))
(define-syntax define-profiling
(syntax-rules ()
((_ (name args ...) body ...)
(define (name args ...)
(begin
(set! *profile*
(cons 'name *profile*))
body ...)))))
(define (profile)
(uniq-c string=?
(sort string<?
(map symbol->string *profile*)))))
As a simple demonstration, here is a function to identify prime numbers by trial division. Function divides? is broken out separately because the profiler only counts function calls, not individual statements.
(define-profiling (divides? d n)
(zero? (modulo n d)))
(define-profiling (prime? n)
(let loop ((d 2))
(cond ((= d n) #t)
((divides? d n) #f)
(else (loop (+ d 1))))))
(define-profiling (prime-pi n)
(let loop ((k 2) (pi 0))
(cond ((< n k) pi)
((prime? k) (loop (+ k 1) (+ pi 1)))
(else (loop (+ k 1) pi)))))
> (prime-pi 1000)
168
> (profile)
(("divides?" . 78022) ("prime-pi" . 1) ("prime?" . 999))
And here is an improved version of the function, which stops trial division at the square root of n:
(define-profiling (prime? n)
(let loop ((d 2))
(cond ((< (sqrt n) d) #t)
((divides? d n) #f)
(else (loop (+ d 1))))))
> (reset-profile)
> (prime-pi 1000)
168
> (profile)
(("divides?" . 5288) ("prime-pi" . 1) ("prime?" . 999))
I'll have more to say about profiling at my blog. Thanks to both #uselpa and #GoZoner for their answers.
Change your line that says:
(set! *profile* (cons name *profile*))
to
(set! *profile* (cons 'name *profile*))
The evaluation of name in the body of a function defining name is the procedure for name. By quoting you avoid the evaluation and are left with the symbol/identifier. As you had hoped, your *profile* variable will be a growing list with one symbol for each function call. You can count the number of occurrences of a given name.
Here's a sample way to implement it. It's written in Racket but trivial to transform to your Scheme dialect.
without syntax
Let's try without macros first.
Here's the profile procedure:
(define profile
(let ((cache (make-hash))) ; the cache memorizing call info
(lambda (cmd . pargs) ; parameters of profile procedure
(case cmd
((def) (lambda args ; the function returned for 'def
(hash-update! cache (car pargs) add1 0) ; prepend cache update
(apply (cadr pargs) args))) ; call original procedure
((dmp) (hash-ref cache (car pargs))) ; return cache info for one procedure
((all) cache) ; return all cache info
((res) (set! cache (make-hash))) ; reset cache
(else (error "wot?")))))) ; unknown parameter
and here's how to use it:
(define test1 (profile 'def 'test1 (lambda (x) (+ x 1))))
(for/list ((i 3)) (test1 i))
=> '(1 2 3)
(profile 'dmp 'test1)
=> 3
adding syntax
(define-syntax define!
(syntax-rules ()
((_ (name args ...) body ...)
(define name (profile 'def 'name (lambda (args ...) body ...))))))
(define! (test2 x) (* x 2))
(for/list ((i 4)) (test2 i))
=> '(0 2 4 6)
(profile 'dmp 'test2)
=> 4
To dump all:
(profile 'all)
=> '#hash((test2 . 4) (test1 . 3))
EDIT applied to your last example:
(define! (divides? d n) (zero? (modulo n d)))
(define! (prime? n)
(let loop ((d 2))
(cond ((< (sqrt n) d) #t)
((divides? d n) #f)
(else (loop (+ d 1))))))
(define! (prime-pi n)
(let loop ((k 2) (pi 0))
(cond ((< n k) pi)
((prime? k) (loop (+ k 1) (+ pi 1)))
(else (loop (+ k 1) pi)))))
(prime-pi 1000)
=> 168
(profile 'all)
=> '#hash((divides? . 5288) (prime-pi . 1) (prime? . 999))

Iterative modulo by repeated subtraction?

I am trying to write an iterative procedure to do modulo arithmetic in scheme without using the built in procedures modulo, remainder or /. However I ran into a few problems while trying to write the code, which looks like this so far:
(define (mod a b)
(define (mod-iter a b)
(cond ((= b 0) 0)
((< b 0) (+ old_b new_b))))
(mod-iter a (- a b)))
As you can see, I ran into the problem of needing to add the original value of b to the current value of b. I am not sure how to go about that. Also, when i left the second conditional's answer to be primitive data (just to make sure the enitre procedure worked), I would get an "unspecified return value" error, and I'm not sure why it happens because the rest of my code loops (or so it seems?)
Thank you in advance for any insight to this.
When you define your mod-iter function with arguments (a b) you are shadowing the arguments defined in mod. To avoid the shadowing, use different identifiers, as such:
(define (mod a b)
(define (mod-iter ax bx)
(cond ((= bx 0) 0)
((< bx 0) (+ b bx))))
(mod-iter a (- a b)))
Note, this doesn't look like the proper algorithm (there is no recursive call). How do you handle the common case of (> bx 0)? You'll need something like:
(define (mod a b)
(define (mod-iter ax bx)
(cond ((= bx 0) 0)
((< bx 0) (+ b bx))
((> bx 0) ...))) ;; <- something here with mod-iter?
(mod-iter a (- a b)))
First if you don't want to capture a variable name, use different variable names in the inner function. Second i think the arguments are wrong compared to the built-in version. (modulo 5 6) is 5 and (modulo 6 5) is 1. Anyways here is a variation in logrirthmic time. That based on generating a list of powers of b (2 4 8 16 32 ...) is b is 2, all the way up to just under the value of a. Then by opportunistically subtracting these reversed values. That way problems like (mod (expt 267 34) 85) return an answer very quickly. (a few hundred primitive function calls vs several million)
(define (mod a-in b-in)
(letrec ((a (abs a-in))
(sign (if (< 0 b-in) - +))
(b (abs b-in))
(powers-list-calc
(lambda (next-exponent)
(cond ((> b a) '())
((= next-exponent 0)
(error "Number 0 passed as the second argument to mod
is not in the correct range"))
(else (cons next-exponent (powers-list (* b next-exponent))))))))
(let ((powers-list (reverse (powers-list-calc b))))
(sign
(let loop ((a a) (powers-L powers-list))
(cond ((null? powers-L) a)
((> a (car powers-L))
(loop (- a (car powers-L)) powers-L))
(else (loop a (cdr powers-L)))))))))

Scheme doing more than one job in one if condition

I am trying to do more than one task in one if condition, here is my code:
(define (dont-tolerate-fools hist0 hist1 hist2 count)
(cond ((> 10 count) 'c)
((< 10 count) (soft-tit-for-tat hist0 hist1 hist2))
((> 10 count) (dont-tolerate-fools hist0 hist1 hist2 (+ 1 count)))))
It didn't work, because I saw that one of the conditions is true it returns it and break. I am trying to make it return 'c for the first 10 time after that it should behave according to something else.
There may be different ways to do it, but I am interesting in how can I do 2 jobs by checking only one if condition?
Thanks in advance.
If you want to do something for the first 10 times you are called, then something else afterwards, the easiest way is to have some kind of "local" variable to count how many times you've been called, such as:
(define func
(let ((count 0))
(lambda ()
(cond
((< count 10)
(set! count (+ count 1))
'a)
(else 'b)))))
(for/list ((i (in-range 15)))
(func))
=> '(a a a a a a a a a a b b b b b)
You can also see in that example that you can have multiple forms or values after the condition:
(cond
((< count 10)
(set! count (+ count 1)) ; action 1
'a) ; action 2
OTOH, if this was simply supposed to be a loop then you're missing a stop condition and one call:
(define (func (n 0))
(cond
((> n 15)
'stop)
((< n 10)
(display 'c)
(func (+ n 1)))
(else
(display 'x)
(func (+ n 1)))))
(func)
=> ccccccccccxxxxxx'stop
The syntax of cond is:
(cond (<predicate> <body> ...)
...)
where <body> ... means that any number of expressions. So you can simply rewrite your code as:
(define (dont-tolerate-fools hist0 hist1 hist2 count)
(cond ((> 10 count)
(dont-tolerate-fools hist0 hist1 hist2 (+ 1 count))
'c)
((< 10 count) (soft-tit-for-tat hist0 hist1 hist2))))

how to check if a number is power of two in Scheme by tail recursion?

(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. :)

Resources