On Wed, Mar 24, 2010 at 8:39 PM, Per Vognsen <per.vogn...@gmail.com> wrote:
> On Wed, Mar 24, 2010 at 8:21 PM, Glen Rubin <rubing...@gmail.com> wrote:
>> I wrote the following code to produce a lazy sequence of the triangle
>> numbers.  (triangle numbers are the series of numbers: 1, 1+2, 1+2+3,
>> etc...)
>>
>> (defn tri-nums []
>>  "prduce a lazy sequence of triangle numbers"
>>  (let [triangles (map #(range 1 %) (iterate inc 2))]
>>    (map #(reduce + %) triangles)))
>>
>> However, I now have produced a large triangle number (76576500) and
>> want to know which triangle number it is (e.g. the first, second,
>> third, etc...)
>
> Why not index the sequence with the 'indexed' function up front?
>
>> So, I wrote the following code which should accept a triangle number
>> as input and tell you which one it is in the series:
>>
>> (defn which-tri [z]
>> (loop [x 1 y (first (tri-nums))]
>>  (cond
>>   (= y z)
>>   x
>>   (< y z)
>>   (recur (inc x) (first (rest (tri-nums))))
>>   true
>>   (println "no such tri-num"))))
>>
>>
>> The problem is that this function works for the first two triangle
>> numbers (1, 3), but then just sits there doing nothing on any higher
>> (6, 10, etc...).

Sorry, I misread your code. I was confused by your variable naming
convention: x is usually the argument to the function.

The problem is actually that your recur always passes the same
unchanging argument for x: (first (rest (tri-nums))). (You also
shouldn't be calling tri-nums from scratch every time.)

-Per

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

To unsubscribe from this group, send email to 
clojure+unsubscribegooglegroups.com or reply to this email with the words 
"REMOVE ME" as the subject.

Reply via email to