Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme Harmonic Function

Tags:

series

sum

scheme

Is there a way to write this function using an if statement instead of cond? The following works as intended, but I was curious to see another option.

(define (harmonic-numbers n)
    (cond ((= n 1) 1)
       ((> n 1) (+ (/ 1 n)
       (harmonic-numbers(- n 1))))))
like image 472
John Friedrich Avatar asked Feb 15 '26 15:02

John Friedrich


1 Answers

Of course, a cond can be implemented as a series of nested ifs. Notice that you have a potential bug in your code, what happens if n is less than 1?

(define (harmonic-numbers n)
  (if (= n 1)
      1
      (if (> n 1)
          (+ (/ 1 n) (harmonic-numbers (- n 1)))
          (error 'undefined))))

Depending on the Scheme interpreter in use, the if form might require you to always provide an "else" part for all conditions (which is why I signaled an error if n is less than 1). Other interpreters are not as strict, and will happily allow you to write a one-armed condition:

(define (harmonic-numbers n)
  (if (= n 1)
      1
      (if (> n 1)
          (+ (/ 1 n) (harmonic-numbers (- n 1))))))

EDIT

Now that we've established what happens if n is less than one, we can write a simpler version using if:

(define (harmonic-numbers n)
  (if (<= n 1)
      1
      (+ (/ 1 n) (harmonic-numbers (- n 1)))))

And here's the equivalent version using cond:

(define (harmonic-numbers n)
  (cond ((<= n 1) 1)
        (else (+ (/ 1 n) (harmonic-numbers (- n 1))))))
like image 109
Óscar López Avatar answered Feb 17 '26 10:02

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!