Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Successive Powers

Tags:

clojure

How would a programmer go along to yield successive powers of two starting at 1 up to a limit?

I saw the documentation http://clojuredocs.org/clojure_core/1.2.0/clojure.core/iterate but still need help. Thanks.

like image 730
user1585646 Avatar asked Mar 30 '26 18:03

user1585646


1 Answers

Separate the task into two steps.

IF you first create a lazy infinite (no need to decide in advance the maximum power you'll need) sequence of powers of 2, you can subsequently slice and dice it any way you choose

(def powers-of-2 (iterate (partial *' 2) 2))

To get the first n powers

(take 5 powers-of-2)

To get the powers less than 70

(take-while (partial > 70) powers-of-2)

Added:

Actually I prefer the more general form:

(defn powers-of [n] (iterate (partial *' n) n))

(take 5 (powers-of 2))

As well as being more general, unless you have efficiency concerns, by calling the higher order function each time for a new lazy sequence you avoid holding on to the head and allow the memory to be garbage collected.

like image 89
status203 Avatar answered Apr 02 '26 10:04

status203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!