// file: toBinaryMSBF.rex // author: Robert Keller // purpose: to convert a number to a list of its binary bits, // most-significant bit first toBinaryMSBF(0) => [0]; toBinaryMSBF(N) => toBinaryMSBFaux(N, []); toBinaryMSBFaux(0, Acc) => Acc; toBinaryMSBFaux(N, Acc) => toBinaryMSBFaux(N/2, [N%2 | Acc]); // Rationale: The number 0 is handled specially, since we don't want // 0 to be converted to [] (no bits). // Acc is an accumulator argument. The bits of the number are determined // least to most, using N%2. As they are, they are cons'ed to the accumulator // N/2 is truncating integer arithmetic, which effectively shifts the binary // representation one place to the right, losing the MSB. // toBinaryMSBFaux is tail recursive test() = map(toBinaryMSBF, range(0, 16));