tech

[English] [Japanese]

04.2. Set

This section describes how to handle a set of LuneScript values, Set.

Difference between Set and Map

A Set manages a set of values, and a Map manages the association between values.

When both are converted to Lua, they are managed as tables, so there is no advantage in using Set over Map in terms of execution speed or memory.

However, using a Set instead of a Map has the following effects:

  • Clarify what your data will be used for
  • No need to deal with Map values unnecessarily
  • Easy to write literal values

Set and Map are the same in the following ways:

  • It does not preserve the order of the values it stores.
  • nilable cannot be stored.

Constructor for Set

Sets generate data by writing:

// @lnsFront: ok
let obj = (@ 1, 2, 3, 4 ); // 1 2 3 4

This is a Set that holds the data 1,2,3,4.

Set encloses values in (@ ).

In addition, the above process omits the type declaration due to type inference, but if you do not omit it, write as follows.

// @lnsFront: ok
let obj:Set<int> = (@ 1, 2, 3, 4 ); // 1 2 3 4

Set<int> declares a Set whose elements are ints.

If you use an empty Set, you must specify the type because it cannot be inferred.

// @lnsFront: ok
let obj:Set<int> = (@);

Working with Sets

Supports the following operations:

  • addition

    • add()
  • delete

    • del()
  • Existence confirmation

    • has()
  • Get number of elements

    • len()
  • duplication

    • clone()

Adding and removing values from a Set works like this:

// @lnsFront: ok
let mut obj = (@ 1, 2, 3, 4 );
obj.add( 0 );  // 0 1 2 3 4
obj.del( 2 );  // 0 1 3 4

The presence or absence of values managed by Set is checked as follows.

// @lnsFront: ok
let obj = (@ 1, 2, 3, 4 );
print( obj.has( 0 ) );  // false
print( obj.has( 1 ) );  // true

Set can get the number of elements with the len() method. However, the len() method enumerates the elements and computes the number, so the complexity is proportional to the size.

// @lnsFront: ok
let mut obj = (@ 1, 2, 3, 4 );
print( obj.len() );

Use clone() to generate the same Set.

// @lnsFront: ok
let obj = (@ 1, 2, 3, 4 );
let obj2 = obj.clone();

clone makes a shallow copy of an element.

Operations between Sets

Supports the following operations:

  • synthesis

    • or()
    • leave the union of two sets
  • common

    • and()
    • leave the intersection of two sets
  • difference

    • sub()
    • keep parts of the current set that do not intersect with the set of arguments

Note that this operation rewrites the contents of the target Set.

// @lnsFront: ok
let set1 = (@  1, 2, 3 );
let set2 = (@  2, 3, 4 );
let set3 = set1.clone().or(set2);   // 1 2 3 4
let set4 = set1.clone().and(set2);  // 2 3 
let set5 = set1.clone().sub(set2);  // 1