(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的参数太多”的错误。
发布于 2020-02-29 10:40:46
这部分代码中有多个错误:
(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)
。if at 2
的格式正确,但肯定不是您想要的(如果<
为true (总是),则为star
(拼写错误,很可能是start
)否则为stop
)。
发布于 2020-03-03 01:07:41
如果我们按照@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
)的方法通常是解决此类问题的关键。
https://stackoverflow.com/questions/60459849
复制