Go to the first, previous, next, last section, table of contents.


Keyval Iterators

Where there is a collection of values, there is a programmer trying to iteratively process them all: When implementing a new type of collection, it is usually a good idea to implement nice facilities for iterating over them as well.

The Muq primitive functions for iterating over the public properties on an object are

getFirstKey??   { obj          -> found? firstKey }
getNextKey??    { obj last-key -> found? nextKey  }

where obj is the object over which we are iterating, found? is nil unless a first/next key existed, last-key is the key to which a successor is desired, and firstKey and nextKey are the next key to use in the iteration.

Using the above, we may write a loop to list out all the public properties on an object:

: list { $ -> }
    -> obj                    ( Save given object.          )
    obj getFirstKey?? do{    ( Get first found?/key pair.  )
        -> key                ( Save key, if we have one.   )
       while                  ( Exit loop if found? is nil. )
       key , "\n" ,           ( List the key.               )
       obj key getNextKey??  ( Try to get the next key.    )
    }
;

The above is workable, but hardly a model of beauty, clarity or conciseness, so Muq MUF provides a control structure to encapsulate the above in sweeter syntax:

: list { $ -> }
    -> obj                    ( Save given object.          )
    obj foreach key do{       ( Get first found?/key pair.  )
       key , "\n" ,           ( List the key.               )
    }
;

The latter compiles into almost exactly the same code as the former, but suppresses a lot of the detail work. So much so that if you're in to mood, you can now fit the function on one line:

: list foreach key do{ key , "\n" , } ;

As a further convenience, foreach will iterate through the values of the keys as well, if you wish:

: list foreach key val do{ key , "\t" , val , "\n" , } ;

(The above function is available in the standard library as ls.)

Analogs of the above are available for each area in an object. For example, hiddenGetFirstKey?? and hiddenGetNextKey?? are the prims iterating over the hidden keyvals in an object, and foreachHidden is the high-level loop which encapsulates them more prettily. See section `keyval functions' in Muf Reference.

Prims also exist to push all the keys and/or vals in an object on the stack as a block: See section `keys[' in Muf Reference, See section `vals[' in Muf Reference, See section `keysvals[' in Muf Reference.


Go to the first, previous, next, last section, table of contents.