[Haskell-beginners] iterated function value sequence

Bob Ippolito bob at redivi.com
Sun Apr 6 16:41:38 UTC 2014


If zz is top-level, then it doesn't know you'll never refer to it again
(the compiler doesn't *have* to keep this around it's hard to know whether
or not it will).

λ> let zz = abs <$> numerator <$> iterate (\x->x^2-7%4) 0
λ> print (zz !! 2)
21
λ> :sprint zz
zz = _ : _ : 21 : _

Note also that iterate is best when you use all of the values up to where
you want to stop (or at least make sure they get evaluated).

If you want to iterate a specific number of times and just get the result,
perhaps foldl' is the way to do it.
λ> abs $ numerator $ foldl' (\x _ -> x^2-7%4) 0 (replicate 7 ())
595096023596888261906480183623645954687

See also:
https://ghc.haskell.org/trac/ghc/ticket/3474
http://stackoverflow.com/questions/8909997/haskell-repeat-a-function-a-large-number-of-times-without-stackoverflow



On Sun, Apr 6, 2014 at 12:44 AM, John M. Dlugosz
<ngnr63q02 at sneakemail.com>wrote:

> On 4/5/2014 10:55 AM, Bob Ippolito wrote:
>
>>     Now, how might I do something like that but "forget" previous values
>> to free up memory?
>>
>>
>> Garbage Collection does that for you. If all the references are gone, the
>> memory can be
>> freed. If you have a specific use in mind I can show you what that looks
>> like.
>>
>>
>>  Say,
>         zz = abs <$> numerator <$> iterate (\x->x^2-7%4) 0
>
> and at some point I
>         print $ zz!!30
>
> How does the GC know that I'll never refer to zz!!n again where n < 30 ?
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140406/6eda3a4b/attachment.html>


More information about the Beginners mailing list