Arc Forumnew | comments | leaders | submitlogin
1 point by cchooper 5618 days ago | link | parent

By the sound of things, the problem is that the variables created by one function are being modified by other functions. In that case, the solution is to use local variables instead of global variables. To do that, you just need to wrap the function body in a single let form:

  (def ugh (str v)
    (let x 15
      (for i 0 (- (len str) 1) (set xi (* x 2))
        (if (is "A" (cut str i (+ i 1)))  
            (set x (+ xi v))
            (set x (- xi v)) i)) x))
The sets will refer to the locally created variable, not a global variable.

  (= x 100000)
  => 100000
  (ugh "AAAA" 1)
  => 255
  x
  => 100000
The global x has not been modified, because the function created a local x variable and used that instead.

Here's a more concise version of that function:

  (def ugh (str v)
    (let x 15
      (on c str 
          (= x (* x 2))
          (if (is #\A c) (++ x v) 
              (-- x v)))
      x))
and here's a version that uses no sets at all:

  (def ugh (str v (o x 15))
    (let x2 (* 2 x)
      (if (is "" str) x
          (is #\A str.0) (ugh (cut str 1) v (+ x2 v))
          (ugh (cut str 1) v (- x2 v)))))


1 point by thaddeus 5618 days ago | link

ah! I see. my rudimentary tests for (= x(...)) and probably having x set from previous iterations of code led me to believe (= x(...)) always changed the global x.

Thanks to all! T.

-----