[Haskell-beginners] why isnt this optimized?

Guillaume Bouchard guillaum.bouchard+haskell at gmail.com
Fri Sep 16 11:52:39 UTC 2016


Glad I was able to help you, some added informations :

On Fri, Sep 16, 2016 at 12:01 PM, Gunnar Quehl <hasquehl at gmx.de> wrote:
> Wow, this reply was much more than I expected. You are my heroe.
> I actually started off with the definition
>
> let fibs = 0:1:zipWith (+) fibs (tail fibs)
>
> and wondered why looking at a certain cell with  for example
>
> fibs !! 20000
>
> always took some amount of time to evaluation, as I expected the
> second time it should be already there. Now I can explain (and do
> something about it, add a type signature).

You can use

:set +s

in ghci to get the time of the line.

Also, you can use :sprint to display the evaluation status of the
thunk, really useful to debug / understand lazyness issues.

Prelude> let l = map (*2) [1::Int ..10]
Prelude> :sprint l
l = _
Prelude> length l
10
Prelude> :sprint l
l = [_,_,_,_,_,_,_,_,_,_]
Prelude> take 3 l
[2,4,6]
Prelude>
Prelude> :sprint l
l = [2,4,6,_,_,_,_,_,_,_]

Finally, recal that (!!) is still an O(n) operator on the fibs list,
but you can build an infinite fibs list with O(n log n) query using an
infinite Tree

see

https://wiki.haskell.org/Memoization#Efficient_tree_data_structure_for_maps_from_Int_to_somewhere


> Thanks that starts to become a good day

;)

-- 
G.


More information about the Beginners mailing list