A Specific Problem With Clojure Closure

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.

test not run
(= 256 ((__ 2) 16),
       ((__ 8) 2))
test not run
(= [1 8 27 64] (map (__ 3) [1 2 3 4]))
test not run
(= [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 powers-of [exponent]
  (iterate #(* % exponent) 1))

(defn nth-power-of [exponent]
  (partial nth (powers-of exponent)))

(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)))

Advertisements

10 Comments

Filed under Clojure

10 responses to “A Specific Problem With Clojure Closure

  1. Jolly

    I tried to avoid Math/pow since it works on doubles:

    #(fn [n]
    (reduce * (repeat % n)))

  2. Malfario

    Reduce is your friend!

  3. another one
    (fn [n] (partial #(Math/pow %2 %1) n))

  4. Despite

    The exponentiating shouldn’t be a problem — use (Math/pow x n)

  5. Octopusgrabbus

    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.

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

  7. Another way of solving the problem –

    (fn [n]
    (fn [x]
    (apply * (repeat n x))))

  8. Here’s alternative soln,

    (fn [n] (fn [x] (apply * (repeat n x))))

  9. i guess the more important thing to note is how to return a function that takes one arg.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s