Reputation: 167
I want to make for-loop using recursion in scheme.
I wrote recursion code which stops at 2, but it doesn't return a
number.
If I write the code in JAVA,
It should be look like this.
global varialbe int i;
public int decreasingNumber( int n)
{
if (n == 2)
return -1
else
{
i = n
return decreasingNumber(n - 1)
}
}
So that I can get changed i, until function reaches 2.
In scheme, I tried
(define (IT n)
(let ((i n ))
(if (= i 2) "done"
(IT(- n 1))
)
)
)
Scheme doesn't let this code work
(+ i 0)
before the recursion.
Upvotes: 0
Views: 53
Reputation: 48745
You are making a global variable in Java and a local in Scheme. If you were to do this:
public static int decreasingNumber(int n) {
if (n == 2) {
return -1;
} else {
int i = n; // dead code
return decreasingNumber(n - 1);
}
}
int minusOne = decreasingNumber(10);
System.out.println(i + 0); // compilation error!!! i doesn't exist
So you see why i
wouldn't exist after calling decreasibngNumber
?
If you want IT
do return something else than the string "done" you shoudl perhaps replace "done" with whatever you want it to return.. eg.
(define (count-down-to-two n)
(if (= n 2)
-1 ; return -1 (why?)
(count-down-to-two (- n 1)))) ; return the result of this recursion
However seeing this can be simplified makes me want to write this instead:
; simplified version
(define (count-down-to-two n)
-1)
Setting global variables (or lexical when closer) can be done with set!
:
(set! i n) ; like i = n in java
Often you can get away by just make the procedure return whateveryou need and make your code functional and easier to test. Go through a book or tutorial to learn how to do it idiomatic rather than trying to use ideas from a totally different family of programming languages (algol family) in the this new language (in the lisp family).
Upvotes: 1