Перейти к содержимому
Топаздокументация
6.05.21

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Загрузка →

    Библиотека · Коллекции

    Array.filter for T

    Keep the elements whose predicate returns true, in iteration order, as an array.

    filter(f: (T) -> bool) -> Array<T>
    Получатель
    Array<T>
    Минимальное число аргументов
    1
    Максимальное число аргументов
    1

    Declaration and parameters

    Доступность

    Включено по умолчанию · Да

    These types are provided by the language. No module import is required.

    The declarations below describe the standard operations on built-in values.

    Получатель

    Array<T>

    Ограничения параметров

    Array<T>, Set<T> and Range values provide map, filter and reduce. A range supplies int elements.

    Each call makes one complete pass over the receiver in its iteration order. Arrays use element order. Sets use insertion order. Ranges use the order of their bounds and step.

    map(f) calls f once per element and returns an array of the results in that order.

    filter(f) calls f once per element and returns an array of the elements for which f returned true, in that order. Set and Range receivers also produce an array.

    reduce(initial, f) starts with initial and calls f with the current accumulator and each element in order. It returns the last accumulator. An empty receiver returns initial without calling f.

    Receiver and callback evaluation, chaining and callback propagation follow the callback and comprehension rule.

    Результат

    The declared result type is Array<T>.

    Эффекты

    Ошибки

    Result and effects

    The predicate runs once per element. The result is an array for every receiver kind.

    Related entries

    Collections →

    Transform arrays, sets and ranges with callbacks

    Правилоtopaz.stdlib.contract.iterable-callbacks.rule

    Transform arrays, sets and ranges with callbacks

    Array<T>, Set<T> and Range values provide map, filter and reduce. A range supplies int elements.

    Each call makes one complete pass over the receiver in its iteration order. Arrays use element order. Sets use insertion order. Ranges use the order of their bounds and step.

    map(f) calls f once per element and returns an array of the results in that order.

    filter(f) calls f once per element and returns an array of the elements for which f returned true, in that order. Set and Range receivers also produce an array.

    reduce(initial, f) starts with initial and calls f with the current accumulator and each element in order. It returns the last accumulator. An empty receiver returns initial without calling f.

    Receiver and callback evaluation, chaining and callback propagation follow the callback and comprehension rule.

    Причина

    A for loop and a comprehension already accept arrays, sets and ranges in the same way. Callback methods accept the same receivers, so the choice between a callback chain and a comprehension follows intent and not the receiver type. map and filter return arrays for every receiver, so a chain has one result shape.

    Observe one pass per array method

    main.tpzObserve one pass per array methodОткрыть песочницу →
    1. import std.io
    2. function scaled(value: int) -> int {
    3. io.writeLine("map {value}")
    4. value * 10
    5. }
    6. function kept(value: int) -> bool {
    7. io.writeLine("filter {value}")
    8. value != 2
    9. }
    10. let values = [1, 2, 3]
    11. let mapped = values.map(scaled)
    12. let selected = values.filter(kept)
    13. let total = values.reduce(100, (sum: int, value: int) => {
    14. io.writeLine("reduce {sum} {value}")
    15. sum - value
    16. })
    17. io.writeLine("{mapped[0]} {mapped[1]} {mapped[2]}")
    18. io.writeLine("{selected.length} {selected[0]} {selected[1]}")
    19. io.writeLine("{total}")
    Ожидаемый выводКод завершения 0
    map 1
    map 2
    map 3
    filter 1
    filter 2
    filter 3
    reduce 100 1
    reduce 99 2
    reduce 97 3
    10 20 30
    2 1 3
    94
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. map 1
    2. map 2
    3. map 3
    4. filter 1
    5. filter 2
    6. filter 3
    7. reduce 100 1
    8. reduce 99 2
    9. reduce 97 3
    10. 10 20 30
    11. 2 1 3
    12. 94

    Transform sets and ranges into arrays

    main.tpzTransform sets and ranges into arraysОткрыть песочницу →
    1. import std.io
    2. let marks = set { 3, 1, 2 }
    3. let doubled: Array<int> = marks.map((value: int) => value * 2)
    4. let large: Array<int> = marks.filter((value: int) => value > 1)
    5. let digits = marks.reduce("", (text: string, value: int) => text + "{value}")
    6. io.writeLine("{doubled[0]} {doubled[1]} {doubled[2]}")
    7. io.writeLine("{large.length} {large[0]} {large[1]}")
    8. io.writeLine(digits)
    9. let squares: Array<int> = (0..<4).map((value: int) => value * value)
    10. let even: Array<int> = (1..6).filter((value: int) => value % 2 == 0)
    11. let number = (1..4).reduce(0, (total: int, value: int) => total * 10 + value)
    12. io.writeLine("{squares.length} {squares[3]}")
    13. io.writeLine("{even.length} {even[0]} {even[2]}")
    14. io.writeLine("{number}")
    Ожидаемый выводКод завершения 0
    6 2 4
    2 3 2
    312
    4 9
    3 2 6
    1234
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 6 2 4
    2. 2 3 2
    3. 312
    4. 4 9
    5. 3 2 6
    6. 1234

    Return empty arrays and the initial value for empty receivers

    main.tpzReturn empty arrays and the initial value for empty receiversОткрыть песочницу →
    1. import std.io
    2. function never(value: int) -> int {
    3. io.writeLine("called {value}")
    4. value
    5. }
    6. let none: Array<int> = []
    7. let nothing: Set<int> = set {}
    8. let mapped = none.map(never)
    9. let selected = nothing.filter((value: int) => never(value) > 0)
    10. let total = (5..<5).reduce(7, (sum: int, value: int) => sum + never(value))
    11. io.writeLine("{mapped.length} {selected.length} {total}")
    Ожидаемый выводКод завершения 0
    0 0 7
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 0 0 7