Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在括号中迷路(Clojure)_Clojure - Fatal编程技术网

在括号中迷路(Clojure)

在括号中迷路(Clojure),clojure,Clojure,请说明如何将以下函数重新构造为可读性更强、括号更少的函数 (defn forwardDifference2nd [fn x h] (-> (/ (+ (- (fn (+ (+ x h) h)) (* (fn (+ x h)) 2.0)) (fn x)) (Math/pow h 2)))) 源代码 以下是一个例子: (defn forwardDifference2nd [f x h] (let [fh #(

请说明如何将以下函数重新构造为可读性更强、括号更少的函数

(defn forwardDifference2nd [fn x h]
  (->
   (/ (+ (-
          (fn (+ (+ x h) h))
          (* (fn (+ x h)) 2.0))
         (fn x))
      (Math/pow h 2))))
源代码

以下是一个例子:

(defn forwardDifference2nd [f x h]
  (let [fh #(f (+ x (* h %)))]
    (/ (+ (fh 2) (* -2 (fh 1)) (f x))
       h h)))
简化:

删除->。。。 将外观相似的表达式分解为局部函数 展平嵌套和与差 替换/。。。数学/功率h 2由/。。。h h 更新:

您的计算可以更一般地表示为

(defn difference-at-depth [f x h depth]
  (if (zero? depth)
    (f x)
    (let [depth (dec depth)]
      (/ (- (difference-at-depth f (+ x h) h depth)
            (difference-at-depth f x h depth))
         h))))

(defn forwardDifference2nd [f x h]
  (difference-at-depth f x h 2))
但这段代码显然更长。另一方面,它更好地显示了数学上正在发生的事情,从这个意义上说,它更具可读性。

使用let局部命名,然后使用命名部分进行计算不仅提高了公式的可读性,而且计算效率也更高

对于重复出现的模式(如多项式中的多项式),请使用名称定义函数

(defn forward-difference-2nd [f x h]
  (let [f_xhh (f (+ x h h))
        f_xh  (f (+ x h))
        f_x   (f x)
        h**2  (* h h)]
    (/ (- f_xhh f_xh f_xh f_x) h**2)))

(defn polynom [coeff x power] (* coeff (Math/pow x power)))

(defn my-polynomial [x]
  (+ (polynom 2 x 4) (polynom 4 x 2) (polynom -5 x 1))) 

(def x 1.0)
(def h 0.1)
(forward-difference-2nd my-polynomial x h)

非常感谢。这段代码更面向计算。Clojure有==来比较数字。在比较float/big/long类型时应该避免出现问题。对于zero,还有一个谓词zero?我同意,使用zero?通常是一个很好的实践,是否将其更新为零?深度
(defn forward-difference-2nd [f x h]
  (let [f_xhh (f (+ x h h))
        f_xh  (f (+ x h))
        f_x   (f x)
        h**2  (* h h)]
    (/ (- f_xhh f_xh f_xh f_x) h**2)))

(defn polynom [coeff x power] (* coeff (Math/pow x power)))

(defn my-polynomial [x]
  (+ (polynom 2 x 4) (polynom 4 x 2) (polynom -5 x 1))) 

(def x 1.0)
(def h 0.1)
(forward-difference-2nd my-polynomial x h)