On Tuesday, April 8, 2014 7:57:10 AM UTC-5, sorin cristea wrote:
>
>
> What exactly you mean by '*The point was you aren't using lazy-seq as
> intended here since you are always creating a singleton sequence*' ? In
> my sum function...I intend to compute sum of elements of a collection.
>
Lazy-seq is intended to build sequences. Generally you'd have each
invocation of lazy-seq produce one or more elements of a sequence. You are
only nominally building a sequence. It is always just one element. You are
reducing a collection to a sum. That is the job of reduce. If you want to
delay evaluation for a given argument, use a thunk or a delay.
(defn my-sum [n] (reduce + (range n)))
(def my-result 100000) ; my-result is 4999950000 (eagerly evaluated)
(def my-thunked-result (fn [] (my-sum 100000))) ; the sum is not
calculated until evaluating (my-thunked-result), answer is not cached
(def my-delayed-result (delay (my-sum 100000))) ; the sum is not
calculated until forcing @my-delayed-result, answer is cached for
subsequent use
> [I]f I [d]o this *(def x **(test-fc ...))*, and then *x,* this is not the
> same thing with *(test-fc ...)* ?, I understand the issue related to time
> to compute this sum, but the same time is taken when I call x, right ?
>
> Yes, that's what I said. Only in the first case evaluation is delayed
until you request the value of `x` and in the second it is requested
immediately to print at the REPL. You might find it instructive to put some
`println`s in your code to see how and when your calculation is progressing
and to use a large but still reasonable size collection, say 1 million
elements.
> Thanks for the hint with trampoline function, really interested .
>
> Sorin.
>
>
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.