How do i find Fibonacci numbers in Scheme? - scheme

(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))
Just having some fun with SICP.
I completely understand the idea of Fibonacci algorithm but this code made me stuck up.
What exactly the last line does in compare to imperative style thing(is this just a basic recursion or)?

The procedure is implementing the Fibonacci series as an iterative process. In this case, fib is the main procedure that calls fib-iter, which does the actual work by means of an iteration. Notice that count is used to control the number of iterations we want, whereas a and b are used to store the results of the Fibonacci series for n-1 and n-2 respectively. The line (fib-iter (+ a b) a (- count 1)) is advancing the iteration to the next values.
Please take the time to read about iterative vs. recursive processes in the book, also read about tail recursion - these are the concepts you need to grasp for really understanding what's happening in the example.
For comparison, let's see how the same procedures would look using a more conventional syntax (Python's):
def fib(n):
return fib_iter(1, 0, n)
def fib_iter(a, b, count):
while count != 0: # same as asking `(if (= count 0) ...)`
a, b = a + b, a # same as passing `(+ a b) a` to recursive call
count -= 1 # same as `(- count 1)`
return b # same as returning `b` at end of recursion
As you see, the fib_iter procedure is simply iterating over a range of values controlled by the count variable, assigning a and b to the next values in the series, up until a number of iterations is completed; at this point the result is in b and is returned.

Related

the sum of the all integers from a to b, What's Wrong With My Code?

The goal is to create a code that will compute the sum of all integers from a to b
and if a > b then it should evaluate to 0.
(define (sum-from-to a b)
(if (> a b)
0
(+ a (sum-from-to (- a 1) b))))
My problem is that when I run this, I run out of memory. What's wrong with my code?
The recursive step is incorrect. Assuming that a <= b the fix is as simple as this:
(define (sum-from-to a b)
(if (> a b)
0
(+ a (sum-from-to (+ a 1) b)))) ; add 1, don't subtract
Think about it, we want a to become closer to b at each step, until it jumps over it. If we decrease a, then it'll move away from b, the exact opposite of what we want. That's why your procedure runs out of memory, a never reached b.
Well, here's one answer a mathematician would give: the sum of all integers from a to b is half of the sum of integers from a to b plus the sum of all integers from b to a. And this is a + b + a + 1 + b - 1 + ... + b + a which is a + b + a + b + ... + a + b. And this in turn is (a + b) * (b - a + 1). So the final sum is (a + b) * (a - b + 1) / 2 therefore. So just write that in Lisp, with the additional condition specified that for b < a:
(define (sum-a-b a b)
(if (> a b)
0
(/ (* (+ a b) (+ (- b a) 1)) 2)))
Of course, what is probably being looked for is either a recursive or an iterative answer. Either of those is a terrible solution to the problem: the recursive answer is terrible in both time & space complexity while the iterative one is merely terrible in terms of time complexity.
People who teach Lisp should stop actively trying to teach people to program badly.

Clojure generating matrices

I am going throw the Clojure for Machine Learning book and I dont understand one part of one function.
(defn square-mat
"Creates a square matrix of size n x n whose
elements are all e. Accepts an option argument
for the matrix implementation"
[n e & {:keys [implementation]
:or {implementation :persistent-vector}}]
(let [repeater #(repeat n %)]
(matrix implementation (-> e repeater repeater))))
(defn id-mat
"Creates an identity matrix of n x n size"
[n]
(let [init (square-mat :clatrix n 0)
identity-f (fn [i j n]
(if (= i j) 1 n))]
(cl/map-indexed identity-f init)))
In this second function, I don't understand this part (if ( = i j) than 1 else n). Why else n? n is size
Look at the definition of clatrix/map-indexed. It takes a function of three arguments (the row index, the column index, and the element in that position), and a matrix.
In the inner function (fn [i j n] (if (= i j) 1 n), n is bound not to the number of the rows in the matrix, but to the value in the position (i, j) - which happens to be always zero because the init matrix was initialized with zeros.
Looks like the book is using a very confusing notation (since n is bound to the number of rows in the matrix in the outer function, it would be better to name the third argument of the inner function x or somehow else), but the function should still work.

division using recursive subtraction

I'm trying to get a function to work that divides two numbers, and returns their quotient.
I need to use recursive subtraction to find the quotient.
I don't really understand how to do this. I think I need a counter variable, which I increment by 1 each time I recurse the function. The problem is, I can only pass two arguments into this function:
(define (divide a b) so I'm not sure how to use the counter.
Can I get some psudeocode help?
Function result <- Divide ( a, b )
counter = 0
while a - b >= 0 do
a = a-b
counter = counter + 1
EndWhile
result = counter
End Function
Algoritm without_title
write "which numbers: "
read a b
result = Divide(a, b)
write "Result: ", result
EndAlgoritm
The counter is implicit in the recursion:
(define (divide n d)
(if (< n d)
0
(+ (divide (- n d) d) 1)))
Here n is the numerator and d is the denominator; we assume neither is negative. Here's an example:
> (divide 27 4)
6
This won't work if d is 0; do you see why?
Thinking recursively can be difficult when you first start. But if you keep plugging away at it, you will eventually learn to think recursively, and then you will wonder why you ever thought it was difficult.

DrRacket procedure body help (boolean-odd? x)

An iterative version of odd? for non-negative integer arguments can be written using and, or, and not. To do so, you have to take advantage of the fact that and and or are special forms that evaluate their arguments in order from left to right, exiting as soon as the value is determined. Write (boolean-odd? x) without using if or cond, but using and, or, not (boolean) instead. You may use + and -, but do not use quotient, remainder, /, etc.
A number is even if two divides it evenly, and odd if there if there is a remainder of one. In general, when you divide a number k by a number n, the remainder is one element of the set {0,1,…n-1}. You can generalize your question by asking whether, when k is divided by n, the remainder is in some privileged set of remainder values. Since this is almost certainly homework, I do not want to provide a direct answer to your question, but I'll answer this more general version, without sticking to the constraints of using only and and or.
(define (special-remainder? k n special-remainders)
(if (< k n)
(member k special-remainders)
(special-remainder? (- k n) special-remainders)))
This special-remainder? recursively divides k by n until a remainder less than n is found. Then n is tested for its specialness. In the case that you're considering, you'll be able to eliminate special-remainders, because you don't need (member k special-remainders). Since you only have one special remainder, you can just check whether k is that special remainder.
A positive odd number can be defined as 1 + 2n. Thus an odd number is:
If x is 1
If x is greater than 1 and x-2 is odd.
Thus one* solution that is tail recursive/iterative looks like this:
(define (odd? x)
(or (= ...) ; #t if 1
(and ... ; #f if less than 1
(odd? ...))); recurse with 2 less
*having played around with it it's many ways to do do this and still have it iterative and without if/cond.

time complexity of the acc function in scheme?

I have been trying to find a tight bound time complexity for this function with respect to just one of the arguments. I thought it was O(p^2) (or rather big theta) but I am not sure anymore.
(define (acc p n)
(define (iter p n result)
(if (< p 1)
result
(iter (/ p 2) (- n 1) (+ result n))))
(iter p n 1))
#sarahamedani, why would this be O(p^2)? It looks like O(log p) to me. The runtime should be insensitive to the value of n.
You are summing a series of numbers, counting down from n. The number of times iter will iterate depends on how many times p can be halved without becoming less than 1. In other words, the position of the leftmost '1' bit in p, minus one, is the number of times iter will iterate. That means the number of times iter runs is proportional to log p.
You might try to eyeball it, or go from it more systematically. Assuming we're doing this from scratch, we should try build a recurrence relation from the function definition.
We can assume, for the moment, a very simple machine model where arithmetic operations and variable lookups are constant time.
Let iter-cost be the name of the function that counts how many steps it takes to compute iter, and let it be a function of p, since iter's termination depends only on p. Then you should be able to write expressions for iter-cost(0). Can you do that for iter-cost(1), iter-cost(2), iter-cost(3), and iter-cost(4)?
More generally, given an p greater than zero, can you express iter-cost(p)? It will be in terms of constants and a recurrent call to iter-cost. If you can express it as a recurrence, then you're in a better position to express it in a closed form.

Resources