Reputation: 3236
My question is ... what would be a good way to update the values of currentRow nextRow bitPosition every time (recur [currentRow nextRow bitPosition])) executes. Right now i am struggling with the fact that I can't just do something easy like this in clojure. Instead i am trapped in this world of pain where I cant even figure out how to set a variable to a new value in a loop.
//I wish i could just do this
currentRow =(get myVector 0)
//here my code
(loop [myVector []]
(let [
rule ruleParam
currentRow currentRowParam
nextRow 2r0
bitPosition 2r0
]
(when (bit-test rule (bit-and currentRow 2r111))
(
(bit-shift-right currentRow 1)
(bit-set nextRow 1)
(inc bitPosition)
))
(when (= false (bit-test rule (bit-and currentRow 2r111)) )
(bit-shift-right currentRow 1)
(bit-set nextRow 1)
(inc bitPosition)
)
(recur [currentRow nextRow bitPosition]))
))
(defn firstFunc [[rule currentRowParam]]
(let [currentRowLocal (bit-shift-left currentRowParam 1) nextRowLocal 2r0 bitPositionLocal 0]
(loop [currentRow currentRowLocal nextRow nextRowLocal bitPosition bitPositionLocal]
(if (< bitPosition 31)
(if (bit-test rule (bit-and currentRow 2r111))
(recur
(bit-shift-right currentRow 1)
(bit-set nextRow bitPosition)
(inc bitPosition)
);end recur
(recur
(bit-shift-right currentRow 1)
nextRow
(inc bitPosition)
);end recur
)
;else
nextRow);end if (< bitPosition 31)
);end loop
);end let
);end defn firstFunc
(firstFunc2 [2r1110 2r11])
Upvotes: 1
Views: 471
Reputation: 13483
The short answer is that you can't.
For example, you have
(bit-shift-right currentRow 1)
(bit-set nextRow 1)
(inc bitPosition)
These expressions do nothing. Let's take the first one
(bit-shift-right currentRow 1)
This returns the value of currentRow
bit-shifted right by 1. It does not change currentRow
. Since you have done nothing with the returned value, it is forgotten.
To use the value returned by a function, you can recur
to a loop
, which is just a let
you can recur
to.
If we recast your code accordingly, we get something like
(loop [myVector []]
(loop [rule ruleParam
currentRow currentRowParam
nextRow 2r0
bitPosition 2r0]
(if (bit-test rule (bit-and currentRow 2r111))
(recur
rule
(bit-shift-right currentRow 1)
(bit-set nextRow 1)
(inc bitPosition))
(recur
rule
(bit-shift-right currentRow 1)
(bit-set nextRow 1)
(inc bitPosition)))
(recur rule currentRow nextRow bitPosition)))
... where the complementary if
conditions have been elided.
This is still nonsense.
loop
are recur
s - so you never
escape it.recur
is never reached, as one of the two above it
is always enacted. You might find the easier problems at 4Clojure help you to get to grips with the language.
Upvotes: 4