KScript documentazione
IT

Lingua

Tradotto automaticamente dall’inglese, che è la versione originale.

imposta campi e metodi

Insiemi come ['tea', 'milk'] as set: ogni elemento una sola volta, con in, + e - che restano veloci a prescindere da quanto cresce l'insieme. I metodi che modificano un insieme restituiscono un nuovo insieme.

Un insieme è un gruppo di elementi in cui ogni elemento compare una sola volta. Aggiungere un elemento che l'insieme ha già non fa nulla, verificare se un elemento è presente è rapido a prescindere da quanto cresce l'insieme, e due insiemi possono essere uniti, confrontati e sottratti l'uno dall'altro. Usa un insieme dove altrimenti chiameresti ->unique() ripetutamente, o controlleresti in su una lunga lista dentro un ciclo.

Scrivi un insieme come una lista e dichiaralo come insieme. as set trasforma una lista in un insieme, e una variabile o un campo dichiarato come set trasforma in insieme qualunque lista le venga assegnata:

<let name="colours" value="['red', 'green', 'red', 'blue'] as set" />
<echo value="$colours" /> <!-- ['red', 'green', 'blue'] because the second 'red' is already in the set -->
<echo value="$colours->count()" /> <!-- 3 -->

<let name="seen" type="set" value="[]" /> <!-- an empty set, ready to fill -->
<set name="seen" op="+=" value="'home'" />
<echo value="'home' in $seen" /> <!-- true -->
$colours = ['red', 'green', 'red', 'blue'] as set
echo $colours            // ['red', 'green', 'blue'] because the second 'red' is already in the set
echo $colours->count()   // 3

$seen: set = []          // an empty set, ready to fill
$seen += 'home'
echo 'home' in $seen     // true

set(of: string) è un insieme i cui elementi sono tutti dello stesso tipo. Ogni elemento viene convertito a quel tipo al momento dell'inserimento, come accade per una lista tipizzata, quindi '2' e 2 finiscono per essere lo stesso elemento in un set(of: int):

<let name="ids" type="set(of: int)" value="['1', '2', 2, 3]" />
<echo value="$ids" /> <!-- [1, 2, 3] because '2' becomes the int 2, which is already there -->
<echo value="$ids->type()" /> <!-- 'set(of: int)' -->

<type name="Post">
  <field name="title" type="string" />
  <field name="tags" type="set(of: string)" default="[]" />
</type>
$ids: set(of: int) = ['1', '2', 2, 3]
echo $ids                // [1, 2, 3] because '2' becomes the int 2, which is already there
echo $ids->type()        // 'set(of: int)'

type Post {
  title: string
  tags: set(of: string) = []
}

Un insieme conserva i suoi elementi nell'ordine in cui sono stati aggiunti per la prima volta, quindi stamparlo, scorrerlo con un ciclo e ->join() danno sempre lo stesso ordine. echo e JSON scrivono un insieme come lista. Per riottenere una lista, scrivi $set as list, oppure ->sort() per una lista ordinata.

Gli elementi si confrontano con ===: stesso tipo e stesso valore. 1 e '1' sono due elementi diversi, e liste e mappe si confrontano in base al loro contenuto, quindi [1, 2] è un solo elemento, non importa quante volte viene aggiunto.

Operatori. + restituisce tutti gli elementi di entrambi i lati e - toglie gli elementi di destra. Il lato destro può essere un insieme o una semplice lista, quindi $colours - ['red'] non richiede as set. += aggiunge un elemento, oppure tutti gli elementi di una lista o di un insieme, e -= ne toglie uno. in chiede se un elemento è nell'insieme. == è vero quando due insiemi contengono gli stessi elementi, in qualunque ordine:

<let name="mine" value="['tea', 'milk'] as set" />
<let name="yours" value="['milk', 'juice']" />
<echo value="$mine + $yours" /> <!-- ['tea', 'milk', 'juice'] because milk is only added once -->
<echo value="$mine - $yours" /> <!-- ['tea'] because milk is in both -->
<echo value="$mine == ['milk', 'tea'] as set" /> <!-- true because order doesn't matter between sets -->
$mine = ['tea', 'milk'] as set
$yours = ['milk', 'juice']
echo $mine + $yours                            // ['tea', 'milk', 'juice'] because milk is only added once
echo $mine - $yours                            // ['tea'] because milk is in both
echo $mine == ['milk', 'tea'] as set           // true because order doesn't matter between sets

+= con una lista a destra aggiunge ciascun elemento della lista, come accade per una lista. Per aggiungere la lista stessa come un unico elemento, come una coppia [row, column], usa ->add([row, column]).

I metodi degli insiemi non modificano mai l'insieme su cui vengono chiamati. Un metodo come ->add() o ->filter() restituisce un nuovo insieme, quindi conservi il risultato oppure concateni il metodo successivo. Il nuovo insieme condivide con quello vecchio tutto ciò che può, quindi $seen += $place in un ciclo resta veloce.

Informazioni su un insieme: count · is_empty · contains · any · all · find · is_subset · overlaps

Aggiungere e togliere: add · remove · union · intersect · difference

Mantenere alcuni elementi: filter · reject

Cambiare ogni elemento: map · each

Combinare in un unico valore: sum · average · max · min · reduce · join · count_by · group_by · sort

Un campo è un dato semplice sul valore, letto con un punto e senza parentesi: $value.name. Un metodo richiede argomenti o esegue un'operazione, e si chiama con ->: $value->name(arguments), oppure passando il valore con la pipe: $value |> name(arguments).

Da KScript.Core

#set->add(items...) → set

Un nuovo set con gli elementi aggiunti. Un elemento che il set ha già resta dov'è.

->add(items...) restituisce un nuovo insieme con gli elementi aggiunti in fondo. Un elemento che l'insieme ha già resta dov'è, quindi aggiungerlo di nuovo non cambia nulla:

<let name="basket" value="['apple', 'pear'] as set" />
<echo value="$basket->add('fig')" /> <!-- ['apple', 'pear', 'fig'] because fig is new -->
<echo value="$basket->add('pear', 'plum')" /> <!-- ['apple', 'pear', 'plum'] because pear is there already -->
<echo value="$basket" /> <!-- ['apple', 'pear'] because ->add() gives a new set and leaves this one alone -->
$basket = ['apple', 'pear'] as set
echo $basket->add('fig')            // ['apple', 'pear', 'fig'] because fig is new
echo $basket->add('pear', 'plum')   // ['apple', 'pear', 'plum'] because pear is there already
echo $basket                        // ['apple', 'pear'] because ->add() gives a new set and leaves this one alone

->add() aggiunge ogni argomento come un unico elemento, quindi una lista viene aggiunta per intero. È così che puoi conservare in un insieme punti come [row, column]:

<let name="visited" value="[] as set" />
<set name="visited" value="$visited->add([0, 1])->add([0, 1])" />
<echo value="$visited->count()" /> <!-- 1 because the second [0, 1] matches the first -->
$visited = [] as set
$visited = $visited->add([0, 1])->add([0, 1])
echo $visited->count()   // 1 because the second [0, 1] matches the first
Esempio
<echo>{ (['apple', 'pear'] as set)->add('fig', 'pear') }</echo>
echo (['apple', 'pear'] as set)->add('fig', 'pear')

#set->all(fn(item)) → bool

Vero quando fn è vero per ogni elemento: ->all(fn(name) => $name->count() > 2). Un set vuoto dà vero.

->all(fn(item)) è vero quando la funzione è vera per ogni elemento. Un insieme vuoto dà true, perché nessun elemento fallisce:

<let name="names" value="['ada', 'grace', 'linus'] as set" />
<echo value="$names->all(fn(name) => $name->count() >= 3)" /> <!-- true because every name has at least 3 letters -->
<echo value="$names->all(fn(name) => $name->count() > 3)" /> <!-- false because ada has only 3 -->
$names = ['ada', 'grace', 'linus'] as set
echo $names->all(fn(name) => $name->count() >= 3)   // true because every name has at least 3 letters
echo $names->all(fn(name) => $name->count() > 3)    // false because ada has only 3
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ (['ada', 'grace'] as set)->all(fn(name) => $name->count() >= 3) }</echo>
echo (['ada', 'grace'] as set)->all(fn(name) => $name->count() >= 3)

#set->any(fn(item)?) → bool

Vero quando fn è vera per un qualunque elemento, oppure, senza fn, quando l'insieme non è vuoto.

->any(fn(item)?) è vero quando la funzione è vera per almeno un elemento. Senza funzione, verifica se l'insieme ha almeno un elemento:

<let name="names" value="['ada', 'grace'] as set" />
<echo value="$names->any(fn(name) => $name->starts_with('g'))" /> <!-- true because grace starts with g -->
<echo value="([] as set)->any()" /> <!-- false because the set is empty -->
$names = ['ada', 'grace'] as set
echo $names->any(fn(name) => $name->starts_with('g'))   // true because grace starts with g
echo ([] as set)->any()                                 // false because the set is empty
ParametroAccetta
fn optionalfn
Esempio
<echo>{ (['ada', 'grace'] as set)->any(fn(name) => $name->starts_with('g')) }</echo>
echo (['ada', 'grace'] as set)->any(fn(name) => $name->starts_with('g'))

#set->average(fn(item)?) → number

La media degli elementi (o di fn per ciascun elemento), oppure null se l'insieme è vuoto.

->average(fn(item)?) somma gli elementi e divide per il loro numero. Con una funzione, calcola la media di ciò che la funzione restituisce per ogni elemento. Un insieme vuoto dà null:

<let name="scores" value="[70, 90, 70, 80] as set" />
<echo value="$scores->average()" /> <!-- 80 because the set holds 70, 90 and 80 once each, and 240 / 3 is 80 -->
$scores = [70, 90, 70, 80] as set
echo $scores->average()   // 80 because the set holds 70, 90 and 80 once each, and 240 / 3 is 80
ParametroAccetta
fn optionalfn
Esempio
<echo>{ ([70, 90, 70, 80] as set)->average() }</echo>
echo ([70, 90, 70, 80] as set)->average()

#set->contains(item) → bool

Vero quando l'elemento è nell'insieme, confrontato con ===. Resta veloce a prescindere da quanto cresce l'insieme, e così fa item in $set.

->contains(item) è vero quando l'elemento è nell'insieme. item in $set chiede la stessa cosa. Entrambi restano veloci a prescindere da quanti elementi contiene l'insieme, ed è questo il motivo per usare un insieme invece di una lista per una lunga serie di cose già viste:

<let name="vowels" value="['a', 'e', 'i', 'o', 'u'] as set" />
<echo value="$vowels->contains('e')" /> <!-- true -->
<echo value="'y' in $vowels" /> <!-- false because y isn't one of the five -->
<echo value="$vowels->contains('E')" /> <!-- false because items match exactly, and 'E' isn't 'e' -->
$vowels = ['a', 'e', 'i', 'o', 'u'] as set
echo $vowels->contains('e')   // true
echo 'y' in $vowels           // false because y isn't one of the five
echo $vowels->contains('E')   // false because items match exactly, and 'E' isn't 'e'
Esempio
<echo>{ (['a', 'e', 'i'] as set)->contains('e') }</echo>
echo (['a', 'e', 'i'] as set)->contains('e')

#set->count() → number

Quanti elementi contiene l'insieme.

->count() restituisce quanti elementi ha l'insieme. Ogni elemento conta una sola volta, non importa quante volte sia stato aggiunto:

<let name="line" value="'rr?gb?r'" />
<echo value="($line->chars() as set)->count()" /> <!-- 4 because the characters are r, ?, g and b -->
<echo value="($line->chars() as set - ['?'])->count()" /> <!-- 3 because taking away ? leaves r, g and b -->
$line = 'rr?gb?r'
echo ($line->chars() as set)->count()           // 4 because the characters are r, ?, g and b
echo ($line->chars() as set - ['?'])->count()   // 3 because taking away ? leaves r, g and b
Esempio
<echo>{ (['red', 'green', 'red'] as set)->count() }</echo>
echo (['red', 'green', 'red'] as set)->count()

#set->count_by(fn(item)) → map

Una mappa dal risultato di fn a quanti elementi lo hanno prodotto.

->count_by(fn(item)) raggruppa gli elementi in base a ciò che restituisce la funzione e conta ogni gruppo. Le chiavi sono i risultati della funzione come testo:

<let name="words" value="['tea', 'toast', 'jam', 'tea'] as set" />
<echo value="$words->count_by(fn(word) => $word->first())" /> <!-- { t: 2, j: 1 } because tea and toast start with t, and tea is only in the set once -->
$words = ['tea', 'toast', 'jam', 'tea'] as set
echo $words->count_by(fn(word) => $word->first())   // { t: 2, j: 1 } because tea and toast start with t, and tea is only in the set once
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ (['tea', 'toast', 'jam'] as set)->count_by(fn(word) => $word->first()) }</echo>
echo (['tea', 'toast', 'jam'] as set)->count_by(fn(word) => $word->first())

#set->difference(other: set|list, symmetric?: bool) → set

Gli elementi che non sono in other, come restituisce $set - $other. Con symmetric, gli elementi presenti in esattamente uno dei due insiemi: prima quelli di questo insieme, poi quelli di other.

->difference(other, symmetric?) restituisce gli elementi che non sono in other, nell'ordine di questo insieme. Toglie ciò che $set - $other toglierebbe. Con symmetric, restituisce gli elementi presenti in esattamente uno dei due insiemi: prima quelli propri di questo insieme, poi quelli dell'altro:

<let name="mine" value="['tea', 'milk', 'sugar'] as set" />
<let name="yours" value="['milk', 'juice']" />
<echo value="$mine->difference($yours)" /> <!-- ['tea', 'sugar'] because milk is in both -->
<echo value="$mine->difference($yours, symmetric)" /> <!-- ['tea', 'sugar', 'juice'] because juice is only in yours -->
$mine = ['tea', 'milk', 'sugar'] as set
$yours = ['milk', 'juice']
echo $mine->difference($yours)              // ['tea', 'sugar'] because milk is in both
echo $mine->difference($yours, symmetric)   // ['tea', 'sugar', 'juice'] because juice is only in yours
ParametroAccetta
other obbligatorioset|list
symmetric facoltativoun flag: symmetric oppure not symmetric

Gli argomenti possono essere con nome: ->difference(…, symmetric: …).

Esempio
<echo>{ (['tea', 'milk'] as set)->difference(['milk', 'juice'], symmetric) }</echo>
echo (['tea', 'milk'] as set)->difference(['milk', 'juice'], symmetric)

#set->each(fn(item)) → set

Richiama fn per ogni elemento, nell'ordine in cui sono stati aggiunti, e restituisce l'insieme.

->each(fn(item)) chiama la funzione una volta per ogni elemento, nell'ordine in cui sono stati aggiunti, e restituisce l'insieme, così puoi continuare a concatenare:

<let name="guests" value="['ada', 'grace', 'ada'] as set" />
<do>$guests->each(fn(guest) {
    echo "Welcome, { $guest }"
  })</do>
<!-- prints Welcome, ada then Welcome, grace because ada is only in the set once -->
$guests = ['ada', 'grace', 'ada'] as set
$guests->each(fn(guest) {
  echo "Welcome, { $guest }"
})
// prints Welcome, ada then Welcome, grace because ada is only in the set once
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ (['ada', 'grace'] as set)->each(fn(name) => $name->upper()) }</echo>
echo (['ada', 'grace'] as set)->each(fn(name) => $name->upper())

#set->filter(fn(item)) → set

Gli elementi per cui fn(item) è vero, come insieme.

->filter(fn(item)) mantiene gli elementi per cui la funzione è vera, come nuovo insieme:

<let name="numbers" value="[3, 8, 3, 12, 5] as set" />
<echo value="$numbers->filter(fn(number) => $number > 4)" /> <!-- [8, 12, 5] because 3 is too small, and it was only in the set once -->
$numbers = [3, 8, 3, 12, 5] as set
echo $numbers->filter(fn(number) => $number > 4)   // [8, 12, 5] because 3 is too small, and it was only in the set once
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ ([3, 8, 12, 5] as set)->filter(fn(number) => $number > 4) }</echo>
echo ([3, 8, 12, 5] as set)->filter(fn(number) => $number > 4)

#set->find(fn(item)) → any

Il primo elemento (nell'ordine in cui sono stati aggiunti) per cui fn(item) è vero, oppure null.

->find(fn(item)) restituisce il primo elemento, nell'ordine in cui sono stati aggiunti, per cui la funzione è vera. Restituisce null quando nessun elemento corrisponde:

<let name="names" value="['ada', 'grace', 'linus'] as set" />
<echo value="$names->find(fn(name) => $name->count() > 3)" /> <!-- 'grace' because ada has only 3 letters -->
<echo value="$names->find(fn(name) => $name->count() > 9)" /> <!-- null because no name is that long -->
$names = ['ada', 'grace', 'linus'] as set
echo $names->find(fn(name) => $name->count() > 3)    // 'grace' because ada has only 3 letters
echo $names->find(fn(name) => $name->count() > 9)    // null because no name is that long
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ (['ada', 'grace'] as set)->find(fn(name) => $name->count() > 3) }</echo>
echo (['ada', 'grace'] as set)->find(fn(name) => $name->count() > 3)

#set->group_by(fn(item)) → map

Una mappa dal risultato di fn a una lista degli elementi che lo hanno prodotto.

->group_by(fn(item)) raggruppa gli elementi in liste in base a ciò che restituisce la funzione, come mappa da ogni risultato ai suoi elementi:

<let name="foods" value="['apple', 'avocado', 'banana', 'apple'] as set" />
<echo value="$foods->group_by(fn(food) => $food->first())" /> <!-- { a: ['apple', 'avocado'], b: ['banana'] } because apple is in the set once -->
$foods = ['apple', 'avocado', 'banana', 'apple'] as set
echo $foods->group_by(fn(food) => $food->first())   // { a: ['apple', 'avocado'], b: ['banana'] } because apple is in the set once
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ (['apple', 'avocado', 'banana'] as set)->group_by(fn(food) => $food->first()) }</echo>
echo (['apple', 'avocado', 'banana'] as set)->group_by(fn(food) => $food->first())

#set->intersect(other: set|list) → set

Gli elementi che sono presenti anche in other, nell'ordine di questo insieme.

->intersect(other) mantiene gli elementi presenti anche in other, nell'ordine di questo insieme. other può essere un insieme o una lista:

<let name="needed" value="['flour', 'eggs', 'milk'] as set" />
<let name="cupboard" value="['eggs', 'rice', 'flour']" />
<echo value="$needed->intersect($cupboard)" /> <!-- ['flour', 'eggs'] because there is no milk in the cupboard -->
$needed = ['flour', 'eggs', 'milk'] as set
$cupboard = ['eggs', 'rice', 'flour']
echo $needed->intersect($cupboard)   // ['flour', 'eggs'] because there is no milk in the cupboard
ParametroAccetta
other obbligatorioset|list
Esempio
<echo>{ (['flour', 'eggs', 'milk'] as set)->intersect(['eggs', 'flour']) }</echo>
echo (['flour', 'eggs', 'milk'] as set)->intersect(['eggs', 'flour'])

#set->is_empty() → bool

Vero quando l'insieme non ha elementi.

->is_empty() è vero quando l'insieme non ha elementi:

<let name="seen" type="set" value="[]" />
<echo value="$seen->is_empty()" /> <!-- true -->
<echo value="$seen->add('home')->is_empty()" /> <!-- false because the new set holds home -->
$seen: set = []
echo $seen->is_empty()               // true
echo $seen->add('home')->is_empty()  // false because the new set holds home
Esempio
<echo>{ ([] as set)->is_empty() }</echo>
echo ([] as set)->is_empty()

#set->is_subset(of: set|list, strict?: bool) → bool

Vero quando ogni elemento è presente anche in of. Con strict, of deve avere almeno un elemento in più. Per un sovrainsieme, invertilo: $big->is_subset(of: $small) chiede il contrario.

->is_subset(of: other, strict?) è vero quando ogni elemento di questo insieme è presente anche in other. Con strict, other deve avere anche almeno un elemento che questo insieme non ha. Per chiedere il contrario, cioè se questo insieme contiene ogni elemento di un altro, invertilo: $small->is_subset(of: $big):

<let name="needed" value="['flour', 'eggs'] as set" />
<let name="have" value="['flour', 'eggs', 'milk']" />
<echo value="$needed->is_subset(of: $have)" /> <!-- true because flour and eggs are both there -->
<echo value="$needed->is_subset(of: $have, strict)" /> <!-- true because have also holds milk -->
<echo value="$needed->is_subset(of: ['eggs'])" /> <!-- false because flour is missing -->
<echo value="$needed->is_subset(of: $needed, strict)" /> <!-- false because a set has nothing more than itself -->
$needed = ['flour', 'eggs'] as set
$have = ['flour', 'eggs', 'milk']
echo $needed->is_subset(of: $have)            // true because flour and eggs are both there
echo $needed->is_subset(of: $have, strict)    // true because have also holds milk
echo $needed->is_subset(of: ['eggs'])         // false because flour is missing
echo $needed->is_subset(of: $needed, strict)  // false because a set has nothing more than itself
ParametroAccetta
of obbligatorioset|list
strict facoltativoun flag: strict oppure not strict

Gli argomenti possono avere un nome: ->is_subset(…, strict: …).

Esempio
<echo>{ (['flour', 'eggs'] as set)->is_subset(of: ['flour', 'eggs', 'milk']) }</echo>
echo (['flour', 'eggs'] as set)->is_subset(of: ['flour', 'eggs', 'milk'])

#set->join(separator?) → string

Gli elementi uniti in un testo (', ' per impostazione predefinita), nell'ordine in cui sono stati aggiunti.

->join(separator?) unisce gli elementi in un testo, nell'ordine in cui sono stati aggiunti, con ', ' tra di loro, a meno che tu non indichi un altro separatore:

<let name="tags" value="['news', 'tech', 'news'] as set" />
<echo value="$tags->join()" /> <!-- 'news, tech' because news is only in the set once -->
<echo value="$tags->join(' / ')" /> <!-- 'news / tech' -->
$tags = ['news', 'tech', 'news'] as set
echo $tags->join()      // 'news, tech' because news is only in the set once
echo $tags->join(' / ') // 'news / tech'
Esempio
<echo>{ (['news', 'tech', 'news'] as set)->join(' / ') }</echo>
echo (['news', 'tech', 'news'] as set)->join(' / ')

#set->map(fn(item)) → set

Un insieme di fn(item) per ogni elemento. Gli elementi che danno lo stesso valore diventano uno solo.

->map(fn(item)) restituisce un nuovo insieme con ciò che la funzione restituisce per ogni elemento. Gli elementi che danno lo stesso valore diventano un unico elemento:

<let name="words" value="['tea', 'jam', 'toast'] as set" />
<echo value="$words->map(fn(word) => $word->count())" /> <!-- [3, 5] because tea and jam both have 3 letters -->
$words = ['tea', 'jam', 'toast'] as set
echo $words->map(fn(word) => $word->count())   // [3, 5] because tea and jam both have 3 letters
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ (['tea', 'jam', 'toast'] as set)->map(fn(word) => $word->count()) }</echo>
echo (['tea', 'jam', 'toast'] as set)->map(fn(word) => $word->count())

#set->max(by?: fn(item)) → any

L'elemento più grande, oppure quello con il valore più grande di by: fn(item).

->max(by?: fn(item)) restituisce l'elemento più grande oppure, con by:, l'elemento il cui valore by: è il più grande. Un insieme vuoto restituisce null:

<echo value="([4, 9, 2] as set)->max()" /> <!-- 9 -->
<let name="people" value="[{ name: 'ada', age: 36 }, { name: 'bo', age: 41 }] as set" />
<echo value="$people->max(by: .age).name" /> <!-- 'bo' because 41 is older than 36 -->
echo ([4, 9, 2] as set)->max()                                  // 9
$people = [{ name: 'ada', age: 36 }, { name: 'bo', age: 41 }] as set
echo $people->max(by: .age).name                                // 'bo' because 41 is older than 36
ParametroAccetta
by facoltativofn
Esempio
<echo>{ ([4, 9, 2] as set)->max() }</echo>
echo ([4, 9, 2] as set)->max()

#set->min(by?: fn(item)) → any

L'elemento più piccolo, oppure quello con il valore più piccolo di by: fn(item).

->min(by?: fn(item)) restituisce l'elemento più piccolo oppure, con by:, l'elemento il cui valore by: è il più piccolo. Un insieme vuoto restituisce null:

<echo value="([4, 9, 2] as set)->min()" /> <!-- 2 -->
<let name="people" value="[{ name: 'ada', age: 36 }, { name: 'bo', age: 41 }] as set" />
<echo value="$people->min(by: .age).name" /> <!-- 'ada' because 36 is younger than 41 -->
echo ([4, 9, 2] as set)->min()                                  // 2
$people = [{ name: 'ada', age: 36 }, { name: 'bo', age: 41 }] as set
echo $people->min(by: .age).name                                // 'ada' because 36 is younger than 41
ParametroAccetta
by facoltativofn
Esempio
<echo>{ ([4, 9, 2] as set)->min() }</echo>
echo ([4, 9, 2] as set)->min()

#set->overlaps(other: set|list) → bool

Vero quando i due hanno almeno un elemento in comune. not $a->overlaps($b) è vero quando non hanno nulla in comune.

->overlaps(other) è vero quando i due insiemi hanno almeno un elemento in comune. not $a->overlaps($b) è vero quando non hanno nulla in comune:

<let name="allergies" value="['nuts', 'milk'] as set" />
<echo value="$allergies->overlaps(['flour', 'milk'])" /> <!-- true because milk is in both -->
<echo value="not $allergies->overlaps(['flour', 'sugar'])" /> <!-- true because they share nothing -->
$allergies = ['nuts', 'milk'] as set
echo $allergies->overlaps(['flour', 'milk'])        // true because milk is in both
echo not $allergies->overlaps(['flour', 'sugar'])   // true because they share nothing
ParametroAccetta
other obbligatorioset|list
Esempio
<echo>{ (['nuts', 'milk'] as set)->overlaps(['flour', 'milk']) }</echo>
echo (['nuts', 'milk'] as set)->overlaps(['flour', 'milk'])

#set->reduce(fn(total, item), initial?) → any

Combina gli elementi, nell'ordine in cui sono stati aggiunti, in un unico valore: fn(totale, elemento) restituisce il nuovo totale, partendo da initial.

->reduce(fn(total, item), initial?) combina gli elementi in un unico valore, nell'ordine in cui sono stati aggiunti. La funzione riceve il totale finora e l'elemento successivo, e restituisce il nuovo totale, partendo da initial:

<let name="prices" value="[3, 5, 3] as set" />
<echo value="$prices->reduce(fn(total, price) => $total + $price, 10)" /> <!-- 18 because the set holds 3 and 5, and 10 + 3 + 5 is 18 -->
$prices = [3, 5, 3] as set
echo $prices->reduce(fn(total, price) => $total + $price, 10)   // 18 because the set holds 3 and 5, and 10 + 3 + 5 is 18
ParametroAccetta
fn obbligatoriofn
initial facoltativoqualsiasi valore

Gli argomenti possono essere nominati: ->reduce(…, initial: …).

Esempio
<echo>{ ([3, 5, 3] as set)->reduce(fn(total, price) => $total + $price, 10) }</echo>
echo ([3, 5, 3] as set)->reduce(fn(total, price) => $total + $price, 10)

#set->reject(fn(item)) → set

Gli elementi per cui fn(elemento) è falso, come insieme.

->reject(fn(item)) mantiene, come nuovo insieme, gli elementi per cui la funzione è falsa. È l'opposto di ->filter():

<let name="numbers" value="[3, 8, 12, 5] as set" />
<echo value="$numbers->reject(fn(number) => $number > 4)" /> <!-- [3] because 8, 12 and 5 are all more than 4 -->
$numbers = [3, 8, 12, 5] as set
echo $numbers->reject(fn(number) => $number > 4)   // [3] because 8, 12 and 5 are all more than 4
ParametroAccetta
fn obbligatoriofn
Esempio
<echo>{ ([3, 8, 12, 5] as set)->reject(fn(number) => $number > 4) }</echo>
echo ([3, 8, 12, 5] as set)->reject(fn(number) => $number > 4)

#set->remove(items...) → set

Un nuovo insieme senza gli elementi. Un elemento che l'insieme non contiene viene ignorato.

->remove(items...) restituisce un nuovo insieme senza gli elementi. Un elemento che l'insieme non contiene viene ignorato:

<let name="basket" value="['apple', 'pear', 'fig'] as set" />
<echo value="$basket->remove('pear')" /> <!-- ['apple', 'fig'] -->
<echo value="$basket->remove('fig', 'kiwi')" /> <!-- ['apple', 'pear'] because there was no kiwi to take away -->
$basket = ['apple', 'pear', 'fig'] as set
echo $basket->remove('pear')           // ['apple', 'fig']
echo $basket->remove('fig', 'kiwi')    // ['apple', 'pear'] because there was no kiwi to take away
Esempio
<echo>{ (['apple', 'pear', 'fig'] as set)->remove('pear') }</echo>
echo (['apple', 'pear', 'fig'] as set)->remove('pear')

#set->sort(compare?: fn(a, b), by?: fn(item), order?: asc|desc) → list

Gli elementi come elenco ordinato: by: fn(item) fornisce la chiave e order: desc mette per primo il più grande.

->sort(compare?, by?, order?) restituisce gli elementi come lista ordinata, perché un ordinamento è compito di una lista. by: indica il valore su cui ordinare, e order: desc mette per primo il più grande:

<let name="scores" value="[70, 90, 70, 80] as set" />
<echo value="$scores->sort()" /> <!-- [70, 80, 90] because each score is in the set once -->
<echo value="$scores->sort(order: desc)" /> <!-- [90, 80, 70] -->
<echo value="$scores->sort()->type()" /> <!-- 'number[]' because ->sort() gives a list -->
$scores = [70, 90, 70, 80] as set
echo $scores->sort()                // [70, 80, 90] because each score is in the set once
echo $scores->sort(order: desc)     // [90, 80, 70]
echo $scores->sort()->type()        // 'number[]' because ->sort() gives a list
ParametroAccetta
compare optionalfn
by facoltativofn
order optionaluna di queste parole: asc|desc

Gli argomenti possono essere nominati: ->sort(…, by: …, order: …).

Esempio
<echo>{ ([70, 90, 70, 80] as set)->sort(order: desc) }</echo>
echo ([70, 90, 70, 80] as set)->sort(order: desc)

#set->sum(fn(item)?) → number

Il totale degli elementi (o di fn per ogni elemento).

->sum(fn(item)?) somma gli elementi, o ciò che la funzione restituisce per ogni elemento. Ogni elemento conta una sola volta:

<let name="coins" value="[1, 2, 2, 5] as set" />
<echo value="$coins->sum()" /> <!-- 8 because the set holds 1, 2 and 5 -->
$coins = [1, 2, 2, 5] as set
echo $coins->sum()   // 8 because the set holds 1, 2 and 5
ParametroAccetta
fn optionalfn
Esempio
<echo>{ ([1, 2, 2, 5] as set)->sum() }</echo>
echo ([1, 2, 2, 5] as set)->sum()

#set->union(other: set|list) → set

Gli elementi di entrambi: prima quelli di questo insieme, poi i nuovi di other. $set + $other dà lo stesso risultato.

->union(other) restituisce tutti gli elementi di entrambi: prima quelli di questo insieme, poi i nuovi di other. Restituisce ciò che restituisce $set + $other:

<let name="mine" value="['tea', 'milk'] as set" />
<echo value="$mine->union(['milk', 'juice'])" /> <!-- ['tea', 'milk', 'juice'] because milk is only added once -->
$mine = ['tea', 'milk'] as set
echo $mine->union(['milk', 'juice'])   // ['tea', 'milk', 'juice'] because milk is only added once
ParametroAccetta
other obbligatorioset|list
Esempio
<echo>{ (['tea', 'milk'] as set)->union(['milk', 'juice']) }</echo>
echo (['tea', 'milk'] as set)->union(['milk', 'juice'])

Metodi da any