2

I'm trying to recursively append a list in clojure. It is to deconstruct a POW function that I created, turning (POW x 3) into (* x (* x x))

I'm a really novice Clojure programmer, and attempting to wrap my head around this problem in Clojure is kind of tough. I have come up with:

(defn do-it [x n]
  (if (= n 0)
  (println x)
  ((dec n) (if (= x 'x))
     (list '* 'x 'x)
     (list '* 'x x))))

Which will not compile or run, but that is where my plan is going. My idea is to decrease n every time you add another (* x to the list.

I have this, which is similar to what I'm trying to do, but does not implement the POW idea into the function:

(defn do-it [x]
  (if (= x 'x)
    (list '* 'x 'x)
    (list '* 'x x)))

Am I on the right path with the first piece of code? Is what I'm trying even possible?

2
  • Do you want to get expression or value of your result? Commented Nov 6, 2012 at 0:22
  • Expression, if I understood your question/what you meant. Commented Nov 6, 2012 at 0:31

3 Answers 3

4

Your posted efforts are pretty far off the mark, I'm afraid. If I were going to write pow by hand, it would look like this:

(defn pow [x n]
  (if (= n 1)
    x
    (list '* x (pow x (dec n)))))
Sign up to request clarification or add additional context in comments.

Comments

1

You can simplify problem if notice that prefix notation can take various number of arguments. Then your function looks like this:

(defn power [x n]
  (cons '* (repeat n x)))

(power 2 3) => (* 2 2 2)
(power 'x 2) => (* x x)

Zero and One base cases covered also, because:

(power 2 1) => (* 2) ; valid result, produces 2
(power 2 0) => (*) ; valid result, produces 1

2 Comments

the input requires it only take two arguments. Because of this, (* x x x) is invalid. It needs to be (* x (* x x))
if it invalid because of condition "only take two arguments" use @amalloy solution.
0
(defn do-it [x n]
  (if (= 1 n)
    x
    (reduce (fn [chain _] `(~'* ~chain))
            `(~'* ~x ~x)
            (range 2 n))))

(do-it 5 10) ->
(* (* (* (* (* (* (* (* (* 5 5)))))))))

(do-it 5 1) ->
5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.