I am familiar with while loops in other languages but here I have written a small function that computes the derivative of a sum of terms but it only does the first 2 I was wondering if there was a way to alter this to take into account more than 2?
expressions, E
, are represented as lists so 2x + 2y + x^3
is represented as (+ (* 2 x) (* 2 y) (expt x 3))
note that I already have functions written to compute the exponential but it is part of a sum and it stops after the first 2
(define (make-sum v1 v2)
(list '+ v1 v2))
(define (diff-sum x E)
(make-sum (diff x (first-operator E)) (diff x (last-operator E))))
In professional-level Racket, for loops are a standard approach to do something to a sequence. For example, the following produces a simple multiplication table:
(define numbers (list 1 2 3 4 5 6))
(for/list ([item numbers])
(list item (* item 2) (* item 3)))
It's a loop that walks through each number, processes it, and produces a new list of results. Fairly standard; almost every programming language has a notion of iteration across a collection.
In the kind of Racket that you'd have to write for an introductory computer science class, you might have to resort to explicit recursion or a higher order function like map instead, depending on your instructor. These other ways of expressing iteration have the same power as the above loop: we just phrase it a little differently.
For example, the same computation to create the small multiplication table above would be expressed as the following with explicit recursion:
(define (my-loop numbers)
(cond [(empty? numbers) '()]
[else
(define item (first numbers))
(cons (list item (* item 2) (* item 3))
(my-loop (rest numbers)))]))
(my-loop numbers)
and implicitly with the use of map
:
(define (f item)
(list item (* item 2) (* item 3)))
(map f numbers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With