1 package lib
2 3 import (
4 "iter"
5 "maps"
6 )
7 8 // Seq is a generic named FUNCTION type: the shape whose instantiation was not
9 // bound. `Gen[V]` returns a literal holding the substituted `func(int32) bool`
10 // while the declared result is `Seq[V]`, and calling the returned value passes a
11 // concrete function where the parameter is `func(V) bool`.
12 type Seq[V comparable] func(yield func(V) bool)
13 14 func Gen[V comparable](v V) (s Seq[V]) {
15 return func(yield func(V) bool) {
16 yield(v)
17 }
18 }
19 20 func SumSeq(v int32) (sum int32) {
21 total := int32(0)
22 Gen[int32](v)(func(x int32) (cont bool) {
23 total = total + x
24 return true
25 })
26 return total
27 }
28 29 // SumValues instantiates maps.Values - a stdlib generic whose own body returns a
30 // func literal while capturing its parameter - and calls it. Instantiating it
31 // used to fail inside its own body:
32 //
33 // cannot use value of type func(yield func(string, int32) bool) as iter.Seq2 in return statement
34 // cannot use value of type func(k string, v int32) (cont bool) as func(K, V) bool in argument
35 func SumValues(m map[string]int32) (sum int32) {
36 total := int32(0)
37 maps.Values(m)(func(v int32) (cont bool) {
38 total = total + v
39 return true
40 })
41 return total
42 }
43 44 func CountPairs(m map[string]int32) (n int32) {
45 c := int32(0)
46 maps.All(m)(func(k string, v int32) (cont bool) {
47 c = c + 1
48 return true
49 })
50 return c
51 }
52 53 func Keys(m map[string]int32) (out []string) {
54 out = []string{:0:4}
55 maps.Keys(m)(func(k string) (cont bool) {
56 out = push(out, k)
57 return true
58 })
59 return out
60 }
61 62 // Collect drives a hand-written iter.Seq, so the interface itself is exercised
63 // without depending on which slices/maps entry points exist on this target
64 // (slices.Collect lives in slices/iter_wasm.mx and is wasm-only).
65 func Collect(seq iter.Seq[int32]) (out []int32) {
66 out = []int32{:0:4}
67 seq(func(v int32) (cont bool) {
68 out = push(out, v)
69 return true
70 })
71 return out
72 }
73 74 // CounterSeq returns an iter.Seq[int32] the way the stdlib does: a func literal
75 // returned as an instantiated generic named function type. Passing the function
76 // SYMBOL Counter directly where iter.Seq[int32] is expected is a separate,
77 // narrower defect (recorded in the work log round 127); a value already of the
78 // parameter's type needs no assignability step and exercises the substitution.
79 func CounterSeq() (s iter.Seq[int32]) {
80 return func(yield func(int32) bool) {
81 for i := int32(0); i < 3; i++ {
82 if !yield(i) {
83 return
84 }
85 }
86 }
87 }
88