Haskell - How much of Pascal39s triangle does this evaluate

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

If I have this constant pascal defined as

pascal :: [[Int]]
pascal = iterate newrow [1]
  where newrow = (zipWith (+) <*> tail) . ([0]++) . (++[0])

And I evaluate pascal !! 50 !! 50 in GHCI, how much of the triangle does this evaulate? Does that laziness mean only the necessary values (plus a bunch of thunks) get calculated?

Answers

Yes, only the elements that are required to compute the element in question are evaluated.

GHCi offers the :sprint and :print debugging commands that can give you some information about what parts of a value have already been evaluated.

On this example:

GHCi> :sprint pascal
pascal = _

(That s because nothing has been evaluated at this point, and thunks are shown as _.)

GHCi> pascal !! 5 !! 5
1

(I m not using 50 because then this example would become too long.)

GHCi> :sprint pascal
pascal = [1] : [_,1] : [_,_,1] : [_,_,_,1] : [_,_,_,_,1] :
         (_ : _ : _ : _ : _ : 1 : _) : _

Now you get a pretty clear idea what parts have been looked at.

Let s try one more:

GHCi> pascal !! 5 !! 4
5
GHCi> :sprint pascal
pascal = [1] : [1,1] : [_,2,1] : [_,_,3,1] : [_,_,_,4,1] :
         (_ : _ : _ : _ : 5 : 1 : _) : _

And another one:

GHCi> pascal !! 10 !! 5
252
GHCi> :sprint pascal
pascal = [1] : [1,1] : [1,2,1] : [1,3,3,1] : [1,4,6,4,1] :
         (1 : 5 : 10 : 10 :   5 :   1 : _) :
         (_ : 6 : 15 : 20 :  15 :   6 : _) :
         (_ : _ : 21 : 35 :  35 :  21 : _) : 
         (_ : _ : _  : 56 :  70 :  56 : _) :
         (_ : _ : _  : _  : 126 : 126 : _) : 
         (_ : _ : _  : _  : _   : 252 : _) : _

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/26729146/how-much-of-pascals-triangle-does-this-evaluate

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils