Seconds "looking to the future"
An example of a funky seq looking to the future might look like this:
(def funky-seq (let [substrate (atom ())] (letfn [(funk [n] (delay (if (odd? n) n @(nth @substrate (inc n)))))] (reset! substrate (map funk (range)))) (map deref @substrate))) user> (take 10 funky-seq) (1 1 3 3 5 5 7 7 9 9)
(cookie for those who make it easier without breaking it. :-))
Of course, if determining the value of an element can include viewing the "future" element, which itself depends on another element, which requires the calculation of an even more remote element ..., disaster could not help.
Euler 14
The main problem is that he tries to use the "look into the future" scheme on the question code aside, this approach does not really solve the problem, because if you decide to start from 1 and go up, you need to consider the branch: a 10 in the Collatz chain can be obtained through the application of any rule (rule n / 2 applied to 20 or rule 3n + 1 , starting from 3 )), In addition, if you want to build your chains up, you must change the rules and either multiply by 2 , or subtract 1 and divide by 3 (applying at each step this rule, which swarm produces an integer - or maybe both of them).
Of course, you could build a tree, not a lazy list, but that would not look like a code sketch in a question, and I would expect that you would end up being an imaginary thing.
The above should be qualified with the remark that you may have an assumption about which “chain building rule” is likely to generate the longest chain, starting at 1 , while the end position remains below a given limit. If so, you should probably prove it right, and then implement it directly (via loop / recur starting at 1 ); without proof, you really cannot claim to have solved the problem.
Michał Marczyk
source share