• Generators In GXScript

    From Lawrence D'Oliveiro@ldo@nz.invalid to comp.lang.postscript on Fri Sep 27 03:34:47 2024
    From Newsgroup: comp.lang.postscript

    GXScript <https://bitbucket.org/ldo17/gxscript> offers Python-style
    generator functions, e.g. the following generates all permutations of
    items in the array that is passed to it as its argument:

    /permute
    # list permute raA iterator
    # given an array of objects, returns an iterator which will
    # return another permutation of those objects each time it
    # is nextrCOed.
    {
    /the_list exch ldef
    {
    the_list length 0 eq
    { # ifelse
    [] yield
    }
    { # ifelse
    0 1 the_list length 1 sub
    { # for
    /i exch ldef
    /sublist the_list length 1 sub array ldef
    sublist 0 the_list 0 i getinterval putinterval
    sublist i the_list i 1 add the_list length 1 sub i sub getinterval putinterval
    sublist permute
    { # forall
    /subresult exch ldef
    /result the_list length array ldef
    result 0 the_list i get put
    result 1 subresult putinterval
    result yield
    }
    forall
    }
    for
    }
    ifelse
    }
    iter
    }
    ddef # permute

    The rCLforallrCY function accepts the result of a generator call as an iterable, so

    [1 2 3] permute {=} forall

    produces output

    [1 2 3]
    [1 3 2]
    [2 1 3]
    [2 3 1]
    [3 1 2]
    [3 2 1]
    --- Synchronet 3.21d-Linux NewsLink 1.2