【问题标题】:Clojure Recursive Log TableClojure 递归日志表
【发布时间】:2020-02-28 22:05:44
【问题描述】:
(ns logtable)
(defn displayLogTable[start stop step]
(if (> start stop) nil
(if < star stop) log10 start)
(displayLogTable ( + start step) stop step)
)
))
(defn -main []
(println "\n Enter your start, stop and step: ")
(let
[ start stop step (Integer/parseInt (read-line))]
(print (displayLogTable start stop step)
)
)
我收到“if 参数过多”错误
我正在尝试实现一个递归函数来打印我的日志表。
【问题讨论】:
标签:
recursion
clojure
logarithm
【解决方案1】:
这部分代码有多个错误:
(defn displayLogTable[start stop step]
(if (> start stop) nil
(if < star stop) log10 start)
(displayLogTable ( + start step) stop step)
)
))
格式化以使其明显:
(defn displayLogTable[start stop step]
(if (> start stop)
nil ; 1
(if < ;2
star
stop)
log10 ; 3
start) ; 4
(displayLogTable (+ start step) stop step))
)) ; to much closing parens
if 的表单太多 (1-4),其中(if predicate then else) 只允许使用三个。 2 处的 if 格式正确,但肯定不是您想要的(如果 < 为真(总是),则 star(错字,很可能是 start)否则 stop)。
【解决方案2】:
如果我们按照@cfrick's answer 暗示的方式更正您的代码,我们会得到类似...
(defn displayLogTable [start stop step]
(if (> start stop)
nil
(if (< start stop)
(Math/log10 start)
(displayLogTable (+ start step) stop step))))
这没有多大意义。我们可以将其简化为...
(defn displayLogTable [start stop step]
(loop [start start]
(cond
(> start stop) nil
(< start stop) (Math/log10 start)
:else (recur ( + start step)))))
同样是徒劳的。看起来您想要start、stop 和step 定义的数字范围的对数序列。在 Clojure 中执行此操作的一种方法是......
(defn displayLogTable [start stop step]
(map
(fn [x] (Math/log10 x))
(range start stop step)))
例如,...
=> (displayLogTable 1 10 1)
(0.0 0.3010299956639812 0.47712125471966244 0.6020599913279624 0.6989700043360189
0.7781512503836436 0.8450980400142568 0.9030899869919435 0.9542425094393249)
请注意,range 包括起点 (0) 但不包括终点 (10)。
Clojure 处理sequences 的方式(map 和range 出现在这里)往往是解决此类问题的关键。