Skip to content

Instantly share code, notes, and snippets.

@Phrancis
Created March 3, 2016 12:26
Show Gist options
  • Select an option

  • Save Phrancis/3ccdde7b04be4263601a to your computer and use it in GitHub Desktop.

Select an option

Save Phrancis/3ccdde7b04be4263601a to your computer and use it in GitHub Desktop.
polynomials-derivatives.clj
; **********
; Here's an interesting use of both the `map` and `partial` functions. We'll define functions that use the `map` function
; to compute the value of an arbitrary polynomial and its derivative for given x values. The polynomials are described
; by a vector of their coefficients.
; Next, we'll define functions that use `partial` to define functions for a specific polynomial and its derivative.
; Finally, we'll demonstrate using the functions.
; The `range` function returns a lazy sequence of integers from an inclusive lower bound to an exclusive upper bound.
; The lower bound defaults to 0, the step size defaults to 1, and the upper bound defaults to infinity.
; **********
(defn- polynomial
"computes the value of a polynomial
with the given coefficients for a given value x"
[coefs x]
; For example, if coefs contains 3 values then exponents is (2 1 0).
(let [exponents (reverse (range (count coefs)))]
; Multiply each coefficient by x raised to the corresponding exponent
; and sum those results
; coefs go into %1 and exponents go into %2
(apply + (map #(* %1 (Math/pow x %2)) coefs exponents))))
(defn- derivative
"computes the value of the derivative of a polynomial
with the given coefficients for a given value x"
[coefs x]
; The coefficients of the derivative function are obtained by
; multiplying all but the last coefficient by its corresponding exponent.
; The extra exponent will be ignored.
(let [exponents (reverse (range (count coefs)))
derivative-coefs (map #(* %1 %2) (butlast coefs) exponents)]
(polynomial derivative-coefs x)))
(def f (partial polynomial [2 1 3])) ; 2x^2 + x + 3
(def f-prime (partial derivative [2 1 3])) ; 4x + 1
(println "f(2) =" (f 2)) ; f(2) = 13.0
(println "f'(2) =" (f-prime 2)) ; f'(2) = 9.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment