i assume this:
"for x 0 power -1"
is not working, hence the problem. how do I write it correctly? the -1 argument is accepted, though so what exactly am i doing here confused :) ?
(def power (nbr power)
(if (is power 0)
1
(if (> power 0)
(let acc nbr
(for x 1 (- power 1)
(= acc (* acc nbr))) acc)
(let acc 1
(for x 0 power -1
(= acc (/ acc nbr))) acc))))
You don't need to nest if expressions in Arc, you can do this:
(if a b
c d
e f
g)
For defining power, it's easier to use a recursive function:
(def power (n p)
(if (is p 0) 1
(> p 0) (* n (power n (- p 1)))
(/ 1 (power n (* -1 p)))))
If you want to use for then the problem is indeed (for x 0 power -1). for only counts up, so (= acc (/ acc nbr)) never gets executed because 0 is already greater than power.
ah solved it now by reversing the variables.
but lets say you have a function where you dont know before hand, how would you solve that?
edit: changed variablename too.
take a look at http://arcfn.com/doc/iteration.html for a list of different iteration functions. since you aren't using the x variable in those for loops there, you could just use repeat:
They aren't ignored, they just don't do anything. for can take any number of arguments: the first is the symbol, the second the start value, the third the end value, and the rest are all the body of the loop. They all get executed in every iteration. For example:
In this case it's not causing a problem. You're allowed to give parameters whatever name you want, but if you name the parameter after the function then you can't call the function from within itself because the name will now refer to the argument.
So if you don't need to call the function recursively, there's no harm. It's just a bit confusing.