更多功能的方法来做到这一点? [英] More functional way to do this?
本文介绍了更多功能的方法来做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个的帖子讨论了汤姆森的悖论,并模拟它在Clojure。
state
函数返回时间= t时灯的状态。
(defn thomsons-lamp []
(iterate(fn [[onoff dur]]
[not onoff](/ dur 2)])
[true 1] ))
(defn state [t]
(let [t-vals(map second(thomsons-lamp))]
(loop [i 1]
(if(< = t(apply +(take i t-vals)))
((comp first last)(take i(thomsons-lamp)))
))))
如何定义一个更清洁的状态
function(最好没有循环/重复)?
解决方案
-
状态中不必要的二次复杂度
- 浮点使用和错误的证据在您的博客帖子。编写的代码应该使用ratio - (state 2)不应该终止...
减少/您的状态
函数的候选人。
(defn thomsons-lamp [
(映射向量(迭代不真)迭代#(* 1/2%)1)))
(defn state [t] s1 t1] [s2 t2]]
(if(> = t1 t)(减少s1)[s2(+ t1 t2)]))
(thomsons-lamp)))
This post of mine discusses Thomson's paradox, and simulates it in Clojure.
The state
function returns the state of the lamp at time = t.
(defn thomsons-lamp []
(iterate (fn [[onoff dur]]
[(not onoff) (/ dur 2)])
[true 1]))
(defn state [t]
(let [t-vals (map second (thomsons-lamp))]
(loop [i 1]
(if (<= t (apply + (take i t-vals)))
((comp first last) (take i (thomsons-lamp)))
(recur (inc i))))))
How do I define a cleaner state
function (preferably without loop/recur)?
解决方案
The only sins here are
- Unnecessary quadratic complexity in
state
- Evidence of floating point usage and error in your blog post. The code as written should be using ratios -- (state 2) should not terminate...
Reduce/reduced would be a good candidate for your state
function.
(defn thomsons-lamp []
(map vector (iterate not true) (iterate #(* 1/2 %) 1)))
(defn state [t]
(reduce (fn [[s1 t1] [s2 t2]]
(if (>= t1 t) (reduced s1) [s2 (+ t1 t2)]))
(thomsons-lamp)))
这篇关于更多功能的方法来做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文