In the first example, consecutive odd elements are grouped into sublists, while each even element is negated.
i1 : L = {1,2,3,5,7,8,10,12,13,17,18,20,21};
|
i2 : sublists(L, odd, toList, minus)
o2 = {{1}, -2, {3, 5, 7}, -8, -10, -12, {13, 17}, -18, -20, {21}}
o2 : List
|
If g or h is omitted, the identity function is used in its place.
i3 : sublists(L, odd, toList)
o3 = {{1}, 2, {3, 5, 7}, 8, 10, 12, {13, 17}, 18, 20, {21}}
o3 : List
|
i4 : sublists(L, odd)
o4 = {{1}, 2, {3, 5, 7}, 8, 10, 12, {13, 17}, 18, 20, {21}}
o4 : List
|
The sublists will belong to the same class as L.
i5 : L = (1,2,3,5,7,8,10,12,13,17,18,20,21); |
i6 : sublists(L, isPrime, , e -> 0)
o6 = {0, (2, 3, 5, 7), 0, 0, 0, (13, 17), 0, 0, 0}
o6 : List
|
Note that g acts on the sublists, not their elements.
i7 : sublists(L, isPrime, plus, e -> 0)
o7 = {0, 17, 0, 0, 0, 30, 0, 0, 0}
o7 : List
|
Because of the grouping of consecutive elements that return true when input to f, sublists(L, f, g, h) is NOT the same as applying g to elements returning true, and applying h to elements returning false. This could be achieved with a simple if-then-else loop, or with apply.
i8 : a = for l in L list if isPrime l then l else -10*l
o8 = {-10, 2, 3, 5, 7, -80, -100, -120, 13, 17, -180, -200, -210}
o8 : List
|
i9 : b = apply(L, l -> if isPrime l then l else -10*l) o9 = (-10, 2, 3, 5, 7, -80, -100, -120, 13, 17, -180, -200, -210) o9 : Sequence |
On the other hand, if we want to group both "true" and "false" elements into sublists, we can achieve this with a second call to sublists, selecting those elements not already grouped by the first sublists command, as long as the original list was not nested.
i10 : X = {1, 3, 5, 2, 4, 7, 1, 3, 4, 4, 5, 4, 7, 9, 13};
|
i11 : sublists(sublists(X, odd), i -> not instance(i, List))
o11 = {{1, 3, 5}, {2, 4}, {7, 1, 3}, {4, 4}, {5}, {4}, {7, 9, 13}}
o11 : List
|
The object sublists is a method function.