开发者

How to create a function that multiplies all numbers between 1 and "x" with dotimes?

开发者 https://www.devze.com 2023-03-12 16:01 出处:网络
I\'m making a function that multiplies all numbers between an 1 input and a \"x\" input with dotimes loop. If you please, check my function and say what\'s wrong since I don\'t know loops very well in

I'm making a function that multiplies all numbers between an 1 input and a "x" input with dotimes loop. If you please, check my function and say what's wrong since I don't know loops very well in Scheme.

(define (product x)
  (let ((result 1))
        (dotimes (temp x)
                 (set! result (* temp (+ result 1))))
 开发者_如何学运维   result))


Use recursion. It is the way to do things in Scheme/Racket. And try to never use set! and other functions that change variables unless there really is no other choice.

Here's a textbook example of recursion in Scheme:

(define factorial
  (lambda (x)
    (if (<= x 1)
        1
        (* x (factorial (- x 1))))))
0

精彩评论

暂无评论...
验证码 换一张
取 消