scheme wrong-type-argument in attempted solution to Euler Project problem 7 - scheme

I've been trying to solve the seventh Euler Project problem. My program looks like this:
(define (add-prime c)
(define (smallest-divisor n) (find-divisor n 2))
(define (find-divisor n test-divisor)
(cond
((> (* test-divisor test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else
(find-divisor n (+ test-divisor 1)))))
(define (divides? a b) (= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
(if (prime? (+ c 1))
(+ c 1)
(add-prime (+ c 1))))
(define (pv v c)
(if (= c (vector-length v))
v
(begin
(vector-set! v c
(add-prime (vector-ref v (- c 1))))
(pv v (+ c 1)))))
(let ((prime-vec (make-vector 10002)))
(vector-set! prime-vec 0 2)
(pv prime-vec 3)
(display v))
The output looks like this:
In procedure add-prime:
In procedure +: Wrong type argument in position 1: #<unspecified>
I'm very confused. By itself, the add-prime procedure works correctly, it's just that when I combine it to create a vector containing 10,002 prime numbers, it returns this error.

You initialize your vector only at the address 0
(let ((prime-vec (make-vector 10002)))
(vector-set! prime-vec 0 2)
but then you go on filling it starting from the address 3
(pv prime-vec 3)
=
(let ((v prime-vec) (c 3))
....
(vector-set! v c
(add-prime (vector-ref v (- c 1))))
....
=
....
(vector-set! prime-vec 3
(add-prime (vector-ref prime-vec 2)))
....
but you haven't initialized the contents of the vector at the address 2, yet.
Racket uses the value 0 for the uninitialized addresses evidently, but your implementation apparently isn't and instead has #<unspecified> there, causing the error.
Start filling the vector from address 1, instead of 3, and it should fix the error.
As a side note, add-prime is really next-prime. Naming is important, good naming can reduce the cognitive load.

I think there is a typo in your code:
(let ((prime-vec (make-vector 10002)))
(vector-set! prime-vec 0 2)
(pv prime-vec 3)
(display prime-vec)) ;; here you want to print the vector
If I run this program in DrScheme, it gives the following result, which seems kinda fantastic:
#(2 0 0 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 ...)

Related

How to do modulo in scheme

How would I do the following in sicp/scheme/dr. racket?
(define (even? n) (= (% n 2) 0))
Currently it seems like that's not a primitive symbol: %: unbound identifier in: %.
This may be the stupidest way in the world to do it, but without a % or bitwise-&1 I am doing (without logs or anything else):
(define (even? n)
(if (< (abs n) 2)
(= n 0)
(even? (- n 2))))
mod is modulo in scheme:
(define (even? n)
(= (modulo n 2) 0))
I think it's a good practice to get comfortable writing your own procedures when it feels like they are "missing". You could implement your own mod as -
(define (mod a b)
(if (< a b)
a
(mod (- a b) b)))
(mod 0 3) ; 0
(mod 1 3) ; 1
(mod 2 3) ; 2
(mod 3 3) ; 0
(mod 4 3) ; 1
(mod 5 3) ; 2
(mod 6 3) ; 0
(mod 7 3) ; 1
(mod 8 3) ; 2
But maybe we make it more robust by supporting negative numbers and preventing caller from divi
(define (mod a b)
(if (= b 0)
(error 'mod "division by zero")
(rem (+ b (rem a b)) b)))
(define (rem a b)
(cond ((= b 0)
(error 'rem "division by zero"))
((< b 0)
(rem a (neg b)))
((< a 0)
(neg (rem (neg a) b)))
((< a b)
a)
(else
(rem (- a b) b))))

MIT-Scheme SICP Exercise_1.11 -- object #t is not applicable

This is my first post on StackOverflow. I have been working on Exercise 1.11 from SICP and feel I have a viable solution. In transferring from paper to Emacs I seem to have some syntax error that I am unaware of. I tried my best to double and triple check the parenthesis and solve it but the terminal is still giving me an 'object #t is not applicable' message. Could someone please point me in the right direction of how to fix the code so I can test its output properly?"
Exercise 1.11: A function f
is defined by the rule that:
f(n)=n
if n<3
, and
f(n)=f(n−1)+2f(n−2)+3f(n−3)
if n>=3
Write a procedure that computes f by means of a recursive process.
Write a procedure that computes f by means of an iterative process.
(define (f-recur n)
(if ((< n 3) n)
(+ (f(- n 1))
(* 2 (f(n-2)))
(* 3 (f(n-3)))))
(define (f-iter n)
(define (counter n)
(if (<= n 3) 0)
(- n 3))
(define (d n) (+ n (* 2 n) (* 3 n)))
(define (c n) (+ d (* 2 n) (* 3 n)))
(define (b n) (+ c (* 2 d) (* 3 n)))
(define (a n) (+ b (* 2 c) (* 3 d)))
(define (f a b c d counter)
(if ((> (+ counter 3) n) a)
(f (+ b (* 2 c) (* 3 d)) a b c (+ counter 1)))))
(cond ((= counter 0) d)
((= counter 1) c)
((= counter 2) b)
((= counter 3) a)
(else (f a b c d counter))))
I'm pretty sure SICP is looking for a solution in the manner of this iterative fibonnacci:
(define (fib n)
(define (helper n a b)
(if (zero? n)
a
(helper (- n 1) b (+ a b))))
(helper n 0 1))
Fibonacci is f(n)=f(n−1)+f(n−2) so I guess f(n)=f(n−1)+2f(n−2)+3f(n−3) can be made exactly the same way with one extra variable. Your iterative solution looks more like Fortran than Scheme. Try avoiding set!.

How to implement Fibonacci with generators?

I'm trying to implement generators to make a list of fibonacci numbers in Scheme, but i can't do it.
I have two functions, the first is a function that returns the Fibonacci numbers in the form of a list and the second is the generator function.
What I have to do is finally transform the Fibonacci function into a generator from a list of Fibonacci numbers.
;FIBONACCI NUMBERS
(define (fib n a b i)
(if
(= i n)
(list b)
(cons b (fib n b (+ a b) (+ i 1)))
)
)
(define (fibonacci n)
(cond
((= n 1) (list 1))
(else (fib n 0 1 1))
)
)
;GENERATOR
(define (generator start stop step)
(let ((current (- start 1)))
(lambda ()
(cond ((>= current stop) #f)
(else
(set! current (+ current step))
current)))))
(define (next generator)
(generator))
When you write generators people will think about the concept of generators in other lamnguages which can easily be implemented in Scheme withcall/cc.
(define-coroutine (fib)
(let loop ((a 0) (b 1))
(yield a)
(loop b (+ a b))))
(fib) ; ==> 0
(fib) ; ==> 1
(fib) ; ==> 1
(fib) ; ==> 2
(fib) ; ==> 3
Now this is kind of like making a stepper out of an iteration. It's up there with streams and transducers. You can make mapping functions that compose operations in series which does the calculations per item instead of doing separate processes generating lots of collections in between each one like chaining map would do. One of the big things in JavaScript the last years has been linked to generators since an early version of await and async were a combination of generators and promises.
Now if you are thinking more in the more general sense a procedure that proces the next value. You could have that as well:
(define fib
(let ((a 0) (b 1))
(lambda ()
(let ((result a))
(set! a b)
(set! b (+ result b))
result))))
(fib) ; ==> 0
(fib) ; ==> 1
(fib) ; ==> 1
(fib) ; ==> 2
(fib) ; ==> 3
As you see this does the deed by updating private bindings. It's more OO than the fancy real generators.
Since Sylwester mentioned streams, here's a stream solution -
(define fib
(stream-cons 0
(stream-cons 1
(stream-add fib
(stream-rest fib)))))
(stream->list (stream-take fib 20))
; '(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)
stream-add will add two (2) streams together using + and stream primitives -
(define (stream-add s1 s2)
(if (or (stream-empty? s1)
(stream-empty? s2))
empty-stream
(stream-cons (+ (stream-first s1)
(stream-first s2))
(stream-add (stream-rest s1)
(stream-rest s2)))))
Or you can take a more generalised approach that allows use of any procedure and any number of streams -
(define ((stream-lift f) . s)
(if (ormap stream-empty? s)
empty-stream
(stream-cons (apply f (map stream-first s))
(apply (stream-lift f) (map stream-rest s)))))
(define stream-add (stream-lift +))

Josephus in Scheme

Where does this implementation of the Josephus problem fall short? For those who are unfamiliar with the Josephus Problem, the goal is to delete every 3rd entry from a circularly linked list until only one remains. In this example I am deleting every "mth" value.
(define (joseph lst)
(let ((m (+ 1 (random (length lst)))))
(define (joseph-h i xlst mlst)
(cond ((<= (length xlst) 1) xlst)
((null? (cdr mlst))
(joseph-h i xlst xlst))
((= i m)
(joseph-h 1 (delete (car mlst) xlst) (cdr mlst)))
(else
(joseph-h (+ i 1) xlst (cdr mlst)))))
(joseph-h 0 lst lst)))
(joseph (list 1 2 3 4 5 6 7))
(define (delete v lst)
(cond ((= v (car lst))
(cdr lst))
(else
(cons (car lst) (delete v (cdr lst))))))
I always end up with the last number of the list as the answer. I know that this is not right.
You're taking the algorithm too literally, by creating a list and deleting elements ("killing" people) from it. A simpler solution would be to use arithmetic operations to model the problem, here's a possible implementation, adapted from my own previous answer:
(define (joseph n k)
(let loop ([i 1]
[acc 0])
(if (> i n)
(add1 acc)
(loop (add1 i)
(modulo (+ acc k) i)))))
For example, to see which position survives in the list '(1 2 3 4 5 6 7) after killing every third person, do this:
(joseph 7 3)
=> 4
Wikipedia provides an interesting discussion regarding the possible solutions for this problem, my solution adapts the simple python function shown, after converting it to tail recursion.
I give three solutions at my blog. The most literal version deletes from a list of n items in steps of m, representing the list as a cyclic list:
(define (cycle xs)
(set-cdr! (last-pair xs) xs) xs)
(define (josephus3 n m)
(let loop ((k (- m 1)) (alive (cycle (range 0 n))) (dead '()))
(cond ((= (car alive) (cadr alive))
(reverse (cons (car alive) dead)))
((= k 1)
(let ((dead (cons (cadr alive) dead)))
(set-cdr! alive (cddr alive))
(loop (- m 1) (cdr alive) dead)))
This does the deletions by actually removing the killed elements from the alive list and placing them on the dead list. The range function is from my Standard Prelude; it returns the integers from 0 to n-1:
(define (range first past . step)
(let* ((xs '()) (f first) (p past)
(s (cond ((pair? step) (car step))
((< f p) 1) (else -1)))
(le? (if (< 0 s) <= >=)))
(do ((x f (+ x s))) ((le? p x) (reverse xs))
(set! xs (cons x xs)))))
The original Josephus problem killed 41 men in steps of 3, leaving the 31st man as the survivor, counting from 1:
(josephus3 41 3)
(2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36
40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 34 15 30)
You might also enjoy the other two versions at my blog.

multiplicative inverse of modulo m in scheme

I've written the code for multiplicative inverse of modulo m. It works for most of the initial cases but not for some. The code is below:
(define (inverse x m)
(let loop ((x (modulo x m)) (a 1))
(cond ((zero? x) #f) ((= x 1) a)
(else (let ((q (- (quotient m x))))
(loop (+ m (* q x)) (modulo (* q a) m)))))))
For example it gives correct values for (inverse 5 11) -> 9 (inverse 9 11) -> 5 (inverse 7 11 ) - > 8 (inverse 8 12) -> #f but when i give (inverse 5 12) it produces #f while it should have been 5. Can you see where the bug is?
Thanks for any help.
The algorithm you quoted is Algorithm 9.4.4 from the book Prime Numbers by Richard Crandall and Carl Pomerance. In the text of the book they state that the algorithm works for both prime and composite moduli, but in the errata to their book they correctly state that the algorithm works always for prime moduli and mostly, but not always, for composite moduli. Hence the failure that you found.
Like you, I used Algorithm 9.4.4 and was mystified at some of my results until I discovered the problem.
Here's the modular inverse function that I use now, which works with both prime and composite moduli, as long as its two arguments are coprime to one another. It is essentially the extended Euclidean algorithm that #OscarLopez uses, but with some redundant calculations stripped out. If you like, you can change the function to return #f instead of throwing an error.
(define (inverse x m)
(let loop ((x x) (b m) (a 0) (u 1))
(if (zero? x)
(if (= b 1) (modulo a m)
(error 'inverse "must be coprime"))
(let* ((q (quotient b x)))
(loop (modulo b x) x u (- a (* u q)))))))
Does it have to be precisely that algorithm? if not, try this one, taken from wikibooks:
(define (egcd a b)
(if (zero? a)
(values b 0 1)
(let-values (((g y x) (egcd (modulo b a) a)))
(values g (- x (* (quotient b a) y)) y))))
(define (modinv a m)
(let-values (((g x y) (egcd a m)))
(if (not (= g 1))
#f
(modulo x m))))
It works as expected:
(modinv 5 11) ; 9
(modinv 9 11) ; 5
(modinv 7 11) ; 8
(modinv 8 12) ; #f
(modinv 5 12) ; 5
I think this is the Haskell code on that page translated directly into Scheme:
(define (inverse p q)
(cond ((= p 0) #f)
((= p 1) 1)
(else
(let ((recurse (inverse (mod q p) p)))
(and recurse
(let ((n (- p recurse)))
(div (+ (* n q) 1) p)))))))
It looks like you're trying to convert it from recursive to tail-recursive, which is why things don't match up so well.
These two functions below can help you as well.
Theory
Here’s how we find the multiplicative inverse d. We want e*d = 1(mod n), which means that ed + nk = 1 for some integer k. So we’ll write a procedure that solves the general equation ax + by = 1, where a and b are given, x and y are variables, and all of these values are integers. We’ll use this procedure to solve ed + nk = 1 for d and k. Then we can throw away k and simply return d.
>
(define (ax+by=1 a b)
(if (= b 0)
(cons 1 0)
(let* ((q (quotient a b))
(r (remainder a b))
(e (ax+by=1 b r))
(s (car e))
(t (cdr e)))
(cons t (- s (* q t))))))
This function is a general solution to an equation in form of ax+by=1 where a and b is given.The inverse-mod function simply uses this solution and returns the inverse.
(define inverse-mod (lambda (a m)
(if (not (= 1 (gcd a m)))
(display "**Error** No inverse exists.")
(if (> 0(car (ax+by=1 a m)))
(+ (car (ax+by=1 a m)) m)
(car (ax+by=1 a m))))))
Some test cases are :
(inverse-mod 5 11) ; -> 9 5*9 = 45 = 1 (mod 11)
(inverse-mod 9 11) ; -> 5
(inverse-mod 7 11) ; -> 8 7*8 = 56 = 1 (mod 11)
(inverse-mod 5 12) ; -> 5 5*5 = 25 = 1 (mod 12)
(inverse-mod 8 12) ; -> error no inverse exists

Resources