How do I transform/operate on a set/sequence?

245 Views Asked by At

I have a set S = { 1, 2, 3, 4, 5 }.

What is the syntax for changing the contents of the set (or rather, creating a new set) by applying a mathematical operation to it e.g. multiplication, power?

1

There are 1 best solutions below

0
On

This sounds like a case for a set comprehension. So you generate f(e) for those elements of s which match a predicate p(e). The general syntax is:

{ f(s) | e in set S & p(e) }

So for example:

{ e*e | e in set {1,2,3,4,5,6} & e mod 2 = 0 } = {4, 16, 36}

There are more complex cases where you bind more than one element from the set, but this is enough to meet your example :)