summaryrefslogtreecommitdiffstats
path: root/tcllib/modules/generator/generator.tcl
blob: 03bf9dad165687a51aeac389a3b9a6be185978be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# generator.tcl --
#
#       Iterators and generators via coroutines.
#
# Copyright (c) 2009 by Neil Madden <nem@cs.nott.ac.uk>
#
# See the file "license.terms" for information on Usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# RCS: @(#) $Id: generator.tcl,v 1.1 2012/08/08 23:23:06 andreas_kupries Exp $
#

package require Tcl         8.6
package provide generator   0.1

namespace eval generator {
    namespace export {[a-z]*}
    namespace ensemble create

    # next generator varName ?varName ..? --
    #
    #   Fetch the next values from a generator, assigning them to variables. If
    #   the generator is exhausted any remaining variables are assigned the
    #   empty string.
    #
    proc next {generator args} {
        set items [takeList [llength $args] $generator]
        uplevel 1 [list lassign $items {*}$args]
    }

    proc takeList {n generator} {
        if {![exists $generator]} { return [list] }
        set ret [list]
        for {set i 0} {$i < $n} {incr i} {
            set item [$generator]
            if {[llength $item] == 0} { break }
            lappend ret [lindex $item 0]
        }
        return $ret
    }


    # foreach varSpec generator ?varSpec generator ...? body --
    #
    #       Iterate over the elements of one or more generator functions. Each
    #       generator is a command that yields successive elements. The syntax
    #       of this construct closely matches that of the built-in foreach
    #       command.
    #
    proc foreach args {
        if {[llength $args] < 3 || ([llength $args] % 2) != 1} {
            Usage "foreach varSpec generator ?varSpec generator ..? body"
        }
        set body [lindex $args end]
        set genSpec [lrange $args 0 end-1]
        set items [list]
        ::foreach {varList generator} $genSpec {
            lappend items [takeList [llength $varList] $generator]
        }

        try {
            # Keep going until all of the generators are exhausted
            # This is the foreach behaviour: empty strings are substituted for
            # exhausted generators.
            while 1 {
                set count 0
                ::foreach {varList generator} $genSpec item $items {
                    incr count [llength $item]
                    uplevel 1 [list lassign $item {*}$varList]
                }
                if {$count == 0} {
                    # All exhausted
                    break
                }
                try {
                    uplevel 1 $body
                } on continue {} {
                    # Continue processing
                } on return {result options} {
                    # increment -level to remove implementation details
                    dict incr options -level
                    return -options $options $result
                }
                set items [list]
                ::foreach {varList generator} $genSpec {
                    lappend items [takeList [llength $varList] $generator]
                }
            }
        } finally {
            # Ensure generators are all cleaned up
            ::foreach {_ generator} $genSpec {
                destroy $generator
            }
        }
        return
    }

    # finally cmd args.. --
    #
    #       Arranges for cmd to be called when the generator is destroyed. This
    #       can be used to perform cleanup in the event that a generator is
    #       terminated early.
    #
    proc finally args {
        set ns [uplevel 1 { namespace current }]
        trace add command [info coroutine] delete [list ::apply [list args $args $ns]]
    }
    proc exists generator { expr {[llength [info commands $generator]] != 0} }
    proc destroy args {
        ::foreach generator $args {
            if {[exists $generator]} { rename $generator "" }
        }
    }
    proc yield args {
        # Each argument is yielded individually as a separate value.
        ::foreach arg $args {
            ::yield [list $arg]
        }
    }

    proc define {name params body} {
        set name [Resolve 1 $name]
        set ns [namespace qualifiers $name]
        set lambda [list $params $body $ns]
        interp alias {} $name {} ::generator::spawn $lambda
        return $name
    }
                ##### PRIVATE METHODS #####

    proc spawn {lambda args} {
        set it [Gensym]
        coroutine $it ::generator::generate $it $lambda $args
    }

    proc generate {name lambda argList} {
        ::yield $name
        apply $lambda {*}$argList
    }

    proc Resolve {level name} {
        if {[string match ::* $name]} { return $name }
        if {[string is integer -strict $level] && $level >= 0} { incr level }
        set ns [uplevel $level { namespace current }]
        if {$ns eq "::"} { return ::$name }
        return $ns\::$name
    }

    proc All {p xs} {
        ::foreach x $xs { if {![{*}$p $x]} { return 0 } }
        return 1
    }

    proc Empty? xs { expr {[llength $xs] == 0} }


    variable Gensymid 0
    proc Gensym {} {
        variable Gensymid
        set prefix [namespace current]::generator
        while {1} {
            set name $prefix[incr Gensymid]
            if {[llength [info commands $name]] == 0} { break }
        }
        return $name
    }

    proc Usage msg {
        return -code error -level 2 "wrong # args: should be \"$msg\""
    }

    proc names {} {
        set pat {[0-9]*}
        return [info commands [namespace current]::generator$pat]
    }

        ##### STANDARD GENERATORS #####

    define map {f xs} {
        # Ensure underlying generator is cleaned up too
        finally destroy $xs
        foreach x $xs { yield [{*}$f $x] }
    }
    define filter {p xs} {
        finally destroy $xs
        foreach x $xs {
            if {[{*}$p $x]} { yield $x }
        }
    }
    proc reduce {f z xs} {
        foreach x $xs { set z [{*}$f $z $x] }
        return $z
    }
    proc foldl {f z xs} { reduce $f $z $xs }
    proc foldr {f z xs} {
        set ys [generator to list $xs]
        for {set i 0} {$i < [llength $ys]} {incr i} {
            set z [{*}$f [lindex $ys end-$i] $z]
        }
        return $z
    }
    define zipWith {f xs ys} {
        finally destroy $xs $ys
        foreach x $xs y $ys { yield [{*}$f $x $y] }
    }
    proc zip {xs ys} { zipWith list $xs $ys }

    proc all {p xs} { 
        and [map $p $xs]
    }
    proc and xs {
        # foldl && true $xs
        # more efficient implementation (bail-out on first non-true element):
        foreach x $xs { if {!$x} { return 0 } }
        return 1
    }
    proc any {p xs} { reduce or 0 [map $p $xs] }
    define concat args {
        ::foreach xs $args { finally destroy $xs }
        ::foreach xs $args {
            foreach x $xs { yield $x }
        }
    }
    define concatMap {f xs} {
        concat {*}[map $f $xs]
    }
    proc drop {n xs} {
        takeList $n $xs
        return $xs
    }
    define dropWhile {p xs} {
        finally destroy $xs
        foreach x $xs {
            if {![{*}$p $x]} { yield $x; break }
        }
        foreach x $xs { yield $x }
    }
    proc contains {elem xs} {
        foreach x $xs { if {$x eq $elem} { return 1 } }
        return 0
    }

    proc foldl1 {f xs} { foldl $f [take 1 $xs] $xs }
    proc foldli {f z xs} { 
        foreach x $xs { set z [{*}$f [incr i] $z $x] }
        return $z
    }
    proc foldri {f z xs} {
        set ys [to list $xs]
        for {set i [llength $ys]} {$i > 0} {incr i -1} {
            set z [{*}$f [incr j] [lindex $ys $i-1] $z]
        }
        return $z
    }
    proc head xs { take 1 $xs }
    proc tail xs { drop 1 $xs }
    proc last xs {
        foreach x $xs { }
        return $x
    }
    define init xs {
        finally destroy $xs
        set last [head $xs]
        foreach x $xs {
            yield $last
            set last $x
        }
    }
    define take {n xs} {
        finally destroy $xs
        foreach x $xs {
            if {[incr i] >= $n} { break }
            yield $x
        }
    }
    define iterate {f x} {
        while 1 {
            yield $x
            set x [{*}$f $x]
        }
    }

    proc Count {x y} { incr x }
    proc length xs { foldl Count 0 $xs }

    proc or {p xs} {
        foreach x $xs { if {[{*}$p $x]} { return 1 } }
        return 0
    }

    proc product xs { foldl ::tcl::mathop::* 1 $xs }
    define repeat {n args} {
        for {set i 0} {$i < $n} {incr i} {
            yield {*}$args
        }
    }
    proc sum xs { foldl ::tcl::mathop::+ 0 $xs }

    define takeWhile {p xs} {
        finally destroy $xs
        foreach x $xs {
            if {[{*}$p $x]} { yield $x }
        }
    }

    define splitWhen {p xs} {
        finally destroy $xs
        set token [list]
        foreach x $xs {
            if {[{*}$p $x]} {
                yield $token
                set token [list]
            } else {
                lappend token $x
            }
        }
        if {[llength $token]} { yield $token }
    }

    define scanl {f z xs} {
        finally destroy $xs
        yield $z
        foreach x $xs {
            set z [{*}$f $z $x]
            yield $z
        }
    }

    # from ?list|dict? xs
    # Converts a list or dictionary into a generator: over elements or key/value
    # pairs.
    namespace eval from {
        namespace export list dict string
        namespace ensemble create

        generator define list xs {
            foreach x $xs { generator yield $x }
        }

        generator define dict d {
            ::dict for {k v} $d { generator yield $k $v }
        }

        generator define string s {
            foreach c [split $s ""] { generator yield $c }
        }
    }

    # to ?list|dict? g
    # Converts a generator into a list or dictionary by extracting all elements.
    # Dictionaries are created by assuming the generator returns a pair of
    # values per element, and using these as the key and value.
    namespace eval to {
        namespace export list dict string
        namespace ensemble create

        proc list g {
            set xs [::list]
            generator foreach x $g { lappend xs $x }
            return $xs
        }

        proc dict g {
            set d [dict create]
            generator foreach {k v} $g { dict set d $k $v }
            return $d
        }

        proc string g {
            set s ""
            generator foreach c $g { append s $c }
            return $s
        }
    }
    # The conversion functions should follow these identity laws:
    # [to list [from list $xs]] == $xs
    # [to dict [from dict $xs]] == $xs

}