本文介绍了创建闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个闭包(函数生成器)来将数字提高到一个大小,而不使用特定的Clojure库来完成这个任务。现在,我可以使用循环.. recur。

 (defn exp1 
[in- exp-multi]
(loop [num in-num exp-multi in-exp-multi]
(if(> exp-multi 1)
)( - exp-multi 1))
num)))

部分提高力量,但仍然坚持的构造需要重复乘一个数自身一些次数。



编辑:



p>这个例子只是为了解决一个问题使用循环。

解决方案

我无法从你的问题中准确地知道你要的是什么,但也许这个?

 (defn powers-of [exponent] 
(iterate#(*%exponent)1 ))

(defn nth-power-of [exponent]
(partial nth(幂的指数)))

5)2);;返回25

我认为 iterate 根据你的描述寻找;它创建了一个应用于种子的函数的延迟序列。


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 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.

这篇关于创建闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 18:35