As a learning tool, I happen to like 4Clojure . It’s not my only learning source, but I have found it quite useful. Problem 107 is driving me crazy. I’ve copied the problems here for local reference, but basically the problem is to define a function that generates a function to raise, for example 16, to 2, using the first example.

( = 256 ( ( __ 2 ) 16 ) ,
( ( __ 8 ) 2 ) )



( = [ 1 8 27 64 ] ( map ( __ 3 ) [ 1 2 3 4 ] ) )



( = [ 1 2 4 8 16 ] ( map #( ( __ % ) 2 ) [ 0 1 2 3 4 ] ) )


I’m not giving up, but it seems to me this solution is not obvious.
(defn powersof [exponent]
(iterate #(* % exponent) 1))
(defn nthpowerof [exponent]
(partial nth (powersof exponent)))
(defn exp1
[innum inexpmulti]
(loop [num innum expmulti inexpmulti]
(if (> expmulti 1)
(recur (* num innum) ( expmulti 1))
num)))
Like this:
Like Loading...
Related
Filed under Clojure
Tagged as 4Clojure, Clojure
I tried to avoid Math/pow since it works on doubles:
#(fn [n]
(reduce * (repeat % n)))
Reduce is your friend!
another one
(fn [n] (partial #(Math/pow %2 %1) n))
The exponentiating shouldn’t be a problem — use (Math/pow x n)
Thanks. In this particular case, I wanted to try this without a library.
Thank you. I appreciate the answers. I’ll go look at them.
I’m making it a point of not asking for help until struggling for a while. I’ve been playing with this on and off for a few days.
My suggestion is to look at how to break down the exponenting into something a bit smaller – using loop/recur is a bit uneccessary for this problem. Think of how you might harness one of the big sequence functions to replicate exponenting. Once you’ve solved that make sure to follow the idea of a closure – you want a function (f n) that returns a function (f x). Let me know if you want any hints.
Another way of solving the problem –
(fn [n]
(fn [x]
(apply * (repeat n x))))
Here’s alternative soln,
(fn [n] (fn [x] (apply * (repeat n x))))
i guess the more important thing to note is how to return a function that takes one arg.