0

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.

2
  • Your java code is incorrect - first, you should not depend on an external attribute for updating the state of a recursion. Second, it'll always return -1, because you're not doing anything with the value returned by the recursion. What was the expected result, say, if I call decreasingNumber(10) ? Commented Sep 29, 2016 at 20:45
  • you can use set! to alter a top-level variable, which must first be defined with define. -- using mutable global variables for such basic tasks is contrary to the spirit of Scheme. if something can be achieved without this, it usually should. Commented Sep 30, 2016 at 17:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.