michaD
michaD

Reputation: 65

Clojure functions within arithmetic expressions

How would one write the following ocaml expression in clojure:

fun x -> (f (x +. dx) -. f x) /. dx

I simplehearted tried the following expression, but that throws an exception:

(defn derivative [dx f]
  (fn [x] 
    (/ (- f [(+ x dx)] f [x]) dx)))

((derivative 0.01 (fn [x] (* x x))) 1)

java.lang.ClassCastException: ableitung$eval5058$fn__5059 cannot be cast to java.lang.Number Numbers.java:135 clojure.lang.Numbers.minus

Upvotes: 1

Views: 93

Answers (1)

Lee
Lee

Reputation: 144136

You need to apply f which you do with (f x y ..). You probably also shouldn't pass a single vector argument into f, although it's impossible to tell without the definition:

(defn derivative [dx f]
  (fn [x] 
    (/ (- (f (+ x dx)) (f x)) dx)))

Upvotes: 4

Related Questions