LazyArray.st
author Claus Gittinger <cg@exept.de>
Wed, 25 Jun 2014 19:02:27 +0200
changeset 3306 b58330b15063
parent 2713 235621fd5dff
child 3845 d3e54fd83dd6
permissions -rw-r--r--
class: LazyArray class definition changed: #initialize

"{ Package: 'stx:libbasic2' }"

ArrayedCollection variableSubclass:#LazyArray
	instanceVariableNames:'valueGenerator'
	classVariableNames:'UncomputedValueSingleton'
	poolDictionaries:''
	category:'Collections-Arrayed'
!

Object subclass:#UncomputedValue
	instanceVariableNames:''
	classVariableNames:''
	poolDictionaries:''
	privateIn:LazyArray
!

!LazyArray class methodsFor:'documentation'!

documentation
"
    An Array which computes its value lazyly (on demand) and remembers those values.

    [author:]
        Claus Gittinger (cg@alan)

    [see also:]
        Lazy
"
!

examples
"
                                                                [exBegin]
    |squares|

    squares := LazyArray new:100.
    squares valueGenerator:[:index | index squared].

    squares at:50.   
    squares inspect.
                                                                [exEnd]
"
! !

!LazyArray class methodsFor:'initialization'!

initialize
    UncomputedValueSingleton isNil ifTrue:[
        UncomputedValueSingleton := UncomputedValue new.
    ]

    "
     self initialize
    "
! !

!LazyArray class methodsFor:'instance creation'!

new:size
    ^ (super new:size) atAllPut:UncomputedValue
! !

!LazyArray methodsFor:'accessing'!

at:index
    |val|

    val := super at:index.
    val == UncomputedValue ifTrue:[
        val := valueGenerator value:index.
        self at:index put:val.
    ].
    ^ val.
!

valueGenerator:aBlock
    valueGenerator := aBlock
! !

!LazyArray class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libbasic2/LazyArray.st,v 1.3 2014-06-25 17:02:27 cg Exp $'
! !


LazyArray initialize!