I want to create a closure (function generator) to raise a number to a power, without using a specific Clojure library to accomplish this task. Right now, I can do this with loop .. recur.
(defn exp1
[in-num in-exp-multi]
(loop [num in-num exp-multi in-exp-multi]
(if (> exp-multi 1)
(recur (* num in-num) (- exp-multi 1))
num)))
I have tried using partial to raise the power, but am still stuck on the construct needed to repeat multiplying a number by itself some number of times. So, I am looking for an example of generating a function and applying it x number of 开发者_Python百科times.
Edit:
The example was simply to solve a problem using loop .. recur. My desire is to solve this with a closure.
I can't tell from your question precisely what you're asking for, but maybe this?
(defn powers-of [exponent]
(iterate #(* % exponent) 1))
(defn nth-power-of [exponent]
(partial nth (powers-of exponent)))
((nth-power-of 5) 2) ;; returns 25
I think iterate
is what you're looking for based on your description; it creates a lazy seq of the function applied over and over to the seed.
This returns a closure over both arguments -
(defn exp1
[in-num in-exp-multi]
(fn []
(loop [num in-num exp-multi in-exp-multi]
(if (> exp-multi 1)
(recur (* num in-num) (- exp-multi 1))
num))))
精彩评论