this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

pkg/list: adding flatten function as a builtin

this commit adds a new builtin to the list package for generating a
flat list from a nested lists by expanding nested lists in place.

for instance

list.Flatten([1, [[2, 3], []], [4]])

results in

[1, 2, 3, 4]

Change-Id: Ia462f7f2db504fd49601a3c77c0fae9387c038c4
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/3460
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>

authored by

xinau and committed by
Marcel van Lohuizen
074cf5de 22a42d4c

+73
+6
cue/builtin_test.go
··· 156 156 test("list", `list.Drop([1, 2, 3, 4], -1)`), 157 157 `_|_(error in call to list.Drop: negative index)`, 158 158 }, { 159 + test("list", `list.Flatten([1, [[2, 3], []], [4]])`), 160 + `[1,2,3,4]`, 161 + }, { 162 + test("list", `list.Flatten("foo")`), 163 + `_|_(error in call to list.Flatten: cannot use value "foo" (type string) as list)`, 164 + }, { 159 165 test("list", `list.Max([1, 2, 3, 4])`), 160 166 `4`, 161 167 }, {
+31
cue/builtins.go
··· 681 681 }() 682 682 }, 683 683 }, { 684 + Name: "Flatten", 685 + Params: []kind{topKind}, 686 + Result: listKind, 687 + Func: func(c *callCtxt) { 688 + xs := c.value(0) 689 + c.ret, c.err = func() (interface{}, error) { 690 + var flatten func(Value) ([]Value, error) 691 + flatten = func(xs Value) ([]Value, error) { 692 + var res []Value 693 + iter, err := xs.List() 694 + if err != nil { 695 + return nil, err 696 + } 697 + for iter.Next() { 698 + val := iter.Value() 699 + if val.Kind() == ListKind { 700 + vals, err := flatten(val) 701 + if err != nil { 702 + return nil, err 703 + } 704 + res = append(res, vals...) 705 + } else { 706 + res = append(res, val) 707 + } 708 + } 709 + return res, nil 710 + } 711 + return flatten(xs) 712 + }() 713 + }, 714 + }, { 684 715 Name: "Take", 685 716 Params: []kind{listKind, intKind}, 686 717 Result: listKind,
+36
pkg/list/list.go
··· 45 45 return x[n:], nil 46 46 } 47 47 48 + // Flatten reports a flattend sequence of the list x by expanding any elements 49 + // that are lists. 50 + // 51 + // For instance: 52 + // 53 + // Flatten([1, [[2, 3], []], [4]]) 54 + // 55 + // results in 56 + // 57 + // [1, 2, 3, 4] 58 + // 59 + func Flatten(xs cue.Value) ([]cue.Value, error) { 60 + var flatten func(cue.Value) ([]cue.Value, error) 61 + flatten = func(xs cue.Value) ([]cue.Value, error) { 62 + var res []cue.Value 63 + iter, err := xs.List() 64 + if err != nil { 65 + return nil, err 66 + } 67 + for iter.Next() { 68 + val := iter.Value() 69 + if val.Kind() == cue.ListKind { 70 + vals, err := flatten(val) 71 + if err != nil { 72 + return nil, err 73 + } 74 + res = append(res, vals...) 75 + } else { 76 + res = append(res, val) 77 + } 78 + } 79 + return res, nil 80 + } 81 + return flatten(xs) 82 + } 83 + 48 84 // Take reports the prefix of length n of list x, or x itself if n > len(x). 49 85 // 50 86 // For instance: