LazyArray.st
author Claus Gittinger <cg@exept.de>
Sat, 02 May 2020 21:40:13 +0200
changeset 5476 7355a4b11cb6
parent 4328 90ffb6ec8a72
permissions -rw-r--r--
#FEATURE by cg class: Socket class added: #newTCPclientToHost:port:domain:domainOrder:withTimeout: changed: #newTCPclientToHost:port:domain:withTimeout:

"
 COPYRIGHT (c) 2003 by Claus Gittinger
              All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
"{ Package: 'stx:libbasic2' }"

"{ NameSpace: Smalltalk }"

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

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

!LazyArray class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 2003 by Claus Gittinger
              All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
!

documentation
"
    An Array which computes its values lazily (on demand) and remembers them.
    Useful if it is relatively expensive to compute an element, 
    and it may be needed again later.

    [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$'
! !


LazyArray initialize!