简体   繁体   中英

Scheme - Recursive addition/subtraction

So, I have three procedures.

(define (addition a)
  (+ a 1))

(define (subtraction b)
  (- b 1))

(define (recursion a b)
  (define a 10)
  (define b 0)

  (if (a > 0)
      (sub1 a)
      (add1 b))
  (if (b > 0)
      (sub1 b)
      (add1 a))
  0)

The first one takes an integer and adds 1 to it. The second one takes an integer and subtracts 1 from it. The third one is supposed to use these two methods and a recursive way, so if I give (recursion 3 0) as input, it should subtract 1 from 3 until it's 0, and add 1 to 0 until it's 3. As you can see, this code isn't running...

I think the base case would be when a reaches 0 or in the other case b reaches 0. Right?

You first two functions have no issues. They're the classic inc and dec functions. Inc for increment and dec for decrement.

Your "recursion" function should not take a and b as arguments and then set their values with define. Generally, you should not set values with define inside a function in scheme (there are lets to do this, and, in this case, it's not necessary). So drop the (define a something) (define b something). The main problem with the function "recursion" is that it's not recursive. A recursive function calls itself. For instance, lets say I recreate your first two functions.

(define (inc a) (+ a 1))
(define (dec a) (+ a 1))

Then I create another function called recursion, but I'll just use one variable for this demo. Let's say that "recursion" will take the number "a".

If a = 5, we just return a . <=== base case

If a < 5, we increment a AND call ourself on the new a . <= recursive case

If a > 5, we decrement a AND call ourself on the new a . <= recursive case

(define (recursion a)
    (if (= a 5)
        a
        (if (< a 5)
            (recursion (inc a))
            (recursion (dec a)))))

To be really fair, moving toward a central base case is generally not what you want to do. You should be thinking about 'consuming' your input. 0, the empty list, or nil, or good base cases. Anything can be a base case, but these values tend to guild your thinking toward a clear algorithm.

Does that help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM