By the way, I'm sure I won't be the first to have told you what an awesome
language system you've cooked up.
On Saturday, December 6, 2014 4:20:17 PM UTC-5, Bill Allen wrote:
>
> Ahh. I see. Thanks.
>
> With the sum function, and by extension any function that deals with
> iterables, is it safe to assume they work without allocating storage for
> the results of the iterable? Maybe a better question would be, are
> functions like filter and sum behaving in a lazy fashion?
>
> On Saturday, December 6, 2014 12:37:44 PM UTC-5, Stefan Karpinski wrote:
>>
>> The issue is that comprehensions pre-allocate their storage and therefore
>> only work when the thing being iterated over has a length method that can
>> tell it how big an array to allocate. You can use the collect function
>> instead:
>>
>> julia> collect(@task fib(4000000))
>> 34-element Array{Any,1}:
>> 0
>> 1
>> 1
>> 2
>> 3
>> 5
>> 8
>> 13
>> 21
>> 34
>> 55
>> 89
>> 144
>> 233
>> 377
>> 610
>> 987
>> 1597
>> 2584
>> 4181
>> 6765
>> 10946
>> 17711
>> 28657
>> 46368
>> 75025
>> 121393
>> 196418
>> 317811
>> 514229
>> 832040
>> 1346269
>> 2178309
>> 3524578
>>
>> julia> filter(iseven, ans)
>> 12-element Array{Any,1}:
>> 0
>> 2
>> 8
>> 34
>> 144
>> 610
>> 2584
>> 10946
>> 46368
>> 196418
>> 832040
>> 3524578
>>
>> julia> sum(ans)
>> 4613732
>>
>>
>> But you can also just use the sum function, which will operate on
>> anything iterable:
>>
>> julia> sum(filter(iseven, @task fib(4000000)))
>> 4613732
>>
>>
>> A while ago I added a bunch of fairly efficient solutions to Project
>> Euler problems to the test suite, including #2, but don't click if you
>> don't want spoilers:
>>
>> https://github.com/JuliaLang/julia/blob/7dd805feb0/test/euler.jl#L9-L20
>>
>>
>>
>> On Sat, Dec 6, 2014 at 12:04 PM, Bill Allen <[email protected]> wrote:
>>
>>> To learn julia, I'm working my way through Project Euler
>>> <https://projecteuler.net/>. For question #2,
>>> <https://projecteuler.net/problem=2> I ran into an issue that I haven't
>>> found a solution to.
>>>
>>> Given a function that computes fibonacci numbers:
>>>
>>> function fib(n)
>>> a,b = 0,1
>>> while(a < n)
>>> produce(a)
>>> a,b=b,a+b
>>> end
>>> end
>>>
>>> I can write a loop that computes the value:
>>>
>>> function fibsum(n)
>>> s = 0
>>> for x in Task(() -> fib(n))
>>> if x % 2 == 0
>>> s = s + x
>>> end
>>> end
>>> s
>>> end
>>>
>>> fibsum(4000000)
>>> 4613732
>>>
>>> Analogously, one can write:
>>>
>>> s = 0
>>> for x in [1,2,3]
>>> s = s + x
>>> end
>>> println(s)
>>> 6
>>>
>>> or more succinctly,
>>>
>>> sum([x for x in [1,2,3]])
>>>
>>> But, when I try that with the fib Task:
>>>
>>> sum([x for x in Task(()->fib(10))])
>>>
>>> I get
>>>
>>> ERROR: `length` has no method matching length(::Task)
>>> in anonymous at no file
>>>
>>> Which confuses me sense the task works nicely in an explicit loop.
>>>
>>> Regards,
>>> Bill
>>>
>>>
>>