views:

77

answers:

1

what is a more efficient way to accomplish this in clojure:

(defn ones
  ([n] (ones n 1 1))
  ([n i res]
    (if (< i n)
      (recur n (inc i) (bit-set res i))
      res)))

preferably it should still "do the right thing" when it comes to numerical type.

+6  A: 

Why not take 2^(X-1) (by setting only the Xth bit) and then subtract 1?

mquander
That gives you the last X bits. ~(2^(width of type - X) - 1) will do it.
Matt Kane
Oh, I see, I mistakenly thought by "first" he meant "least significant."
mquander
I do want the least significan bits. (ones 4) => 15
Arthur Ulfeldt
Will exponentiation really be faster than a sequence of bit-shifts?
Hank Gay
the code for this is (defn ones [x] (- (bit-set 0 x) 1) thanks!
Arthur Ulfeldt
@Hank, yes, exponentiation of 2 can usually be assumed to be translated to bitshifts by the compiler.
Svante
Doh! It didn't register that the base was 2, even though that's obviously the only way for this to work.
Hank Gay