Iteration utilities

Base.Iterators.StatefulType
Stateful(itr)

이 반복자 래퍼에 대해 생각할 수 있는 몇 가지 방법이 있습니다:

  1. 반복자와 그 반복 상태에 대한 가변 래퍼를 제공합니다.
  2. 반복자와 유사한 추상화를 Channel과 유사한 추상화로 변환합니다.
  3. 항목이 생성될 때마다 자신의 나머지 반복자가 되도록 변형되는 반복자입니다.

Stateful은 일반적인 반복자 인터페이스를 제공합니다. 다른 가변 반복자(예: Base.Channel)와 마찬가지로, 반복이 조기에 중단되면(예: for 루프에서 break로) 동일한 반복자 객체를 계속 반복하여 동일한 지점에서 반복을 재개할 수 있습니다(대조적으로, 불변 반복자는 처음부터 다시 시작합니다).

예제

julia> a = Iterators.Stateful("abcdef");

julia> isempty(a)
false

julia> popfirst!(a)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

julia> collect(Iterators.take(a, 3))
3-element Vector{Char}:
 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)

julia> collect(a)
2-element Vector{Char}:
 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
 'f': ASCII/Unicode U+0066 (category Ll: Letter, lowercase)

julia> Iterators.reset!(a); popfirst!(a)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

julia> Iterators.reset!(a, "hello"); popfirst!(a)
'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)
julia> a = Iterators.Stateful([1,1,1,2,3,4]);

julia> for x in a; x == 1 || break; end

julia> peek(a)
3

julia> sum(a) # 남은 요소의 합계
7
source
Base.Iterators.zipFunction
zip(iters...)

여러 이터레이터를 동시에 실행하며, 그 중 하나가 소진될 때까지 진행합니다. zip 이터레이터의 값 유형은 하위 이터레이터의 값 튜플입니다.

Note

zip은 상태가 있는 이터레이터가 현재 반복에서 다른 이터레이터가 완료될 때 진행되지 않도록 하위 이터레이터에 대한 호출을 정렬합니다.

Note

인수가 없는 zip()은 빈 튜플의 무한 이터레이터를 생성합니다.

참고: enumerate, Base.splat.

예제

julia> a = 1:5
1:5

julia> b = ["e","d","b","c","a"]
5-element Vector{String}:
 "e"
 "d"
 "b"
 "c"
 "a"

julia> c = zip(a,b)
zip(1:5, ["e", "d", "b", "c", "a"])

julia> length(c)
5

julia> first(c)
(1, "e")
source
Base.Iterators.enumerateFunction
enumerate(iter)

1부터 시작하는 카운터 i와 주어진 반복자에서 i번째 값 x를 포함하는 (i, x)를 생성하는 반복자입니다. 반복하고 있는 값 x뿐만 아니라 지금까지의 반복 횟수도 필요할 때 유용합니다.

iiter의 인덱싱에 유효하지 않거나 다른 요소를 인덱싱할 수 있습니다. 이는 iter의 인덱스가 1에서 시작하지 않을 때 발생하며, 문자열, 사전 등에서 발생할 수 있습니다. i가 인덱스가 되도록 하려면 pairs(IndexLinear(), iter) 메서드를 참조하세요.

예제

julia> a = ["a", "b", "c"];

julia> for (index, value) in enumerate(a)
           println("$index $value")
       end
1 a
2 b
3 c

julia> str = "naïve";

julia> for (i, val) in enumerate(str)
           print("i = ", i, ", val = ", val, ", ")
           try @show(str[i]) catch e println(e) end
       end
i = 1, val = n, str[i] = 'n'
i = 2, val = a, str[i] = 'a'
i = 3, val = ï, str[i] = 'ï'
i = 4, val = v, StringIndexError("naïve", 4)
i = 5, val = e, str[i] = 'v'
source
Base.Iterators.countfromFunction
countfrom(start=1, step=1)

시작 start에서 시작하여 step만큼 증가하는 무한 카운트 이터레이터입니다.

예제

julia> for v in Iterators.countfrom(5, 2)
           v > 10 && break
           println(v)
       end
5
7
9
source
Base.Iterators.takeFunction
take(iter, n)

iter의 처음 n 요소를 최대한 생성하는 반복자입니다.

참고: drop, peel, first, Base.take!.

예제

julia> a = 1:2:11
1:2:11

julia> collect(a)
6-element Vector{Int64}:
  1
  3
  5
  7
  9
 11

julia> collect(Iterators.take(a,3))
3-element Vector{Int64}:
 1
 3
 5
source
Base.Iterators.takewhileFunction
takewhile(pred, iter)

iter에서 pred가 참인 동안 요소를 생성하는 반복자이며, 그 이후에는 모든 요소를 버립니다.

Julia 1.4

이 함수는 최소한 Julia 1.4가 필요합니다.

예제

julia> s = collect(1:5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> collect(Iterators.takewhile(<(3),s))
2-element Vector{Int64}:
 1
 2
source
Base.Iterators.dropFunction
drop(iter, n)

iter의 첫 번째 n 요소를 제외한 모든 요소를 생성하는 반복자입니다.

예제

julia> a = 1:2:11
1:2:11

julia> collect(a)
6-element Vector{Int64}:
  1
  3
  5
  7
  9
 11

julia> collect(Iterators.drop(a,4))
2-element Vector{Int64}:
  9
 11
source
Base.Iterators.dropwhileFunction
dropwhile(pred, iter)

iter에서 pred가 참인 동안 요소를 제거하고, 그 이후에는 모든 요소를 반환하는 반복자입니다.

Julia 1.4

이 함수는 최소한 Julia 1.4가 필요합니다.

예제

julia> s = collect(1:5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> collect(Iterators.dropwhile(<(3),s))
3-element Vector{Int64}:
 3
 4
 5
source
Base.Iterators.cycleFunction
cycle(iter[, n::Int])

iter를 영원히 순환하는 반복자입니다. n이 지정되면, iter를 그만큼 순환합니다. iter가 비어 있으면, cycle(iter)cycle(iter, n)도 비어 있습니다.

Iterators.cycle(iter, n)Base.repeat(vector, n)의 지연된 동등물이며, Iterators.repeated(iter, n)은 지연된 Base.fill(item, n)입니다.

Julia 1.11

cycle(iter, n) 메서드는 Julia 1.11에 추가되었습니다.

예제

julia> for (i, v) in enumerate(Iterators.cycle("hello"))
           print(v)
           i > 10 && break
       end
hellohelloh

julia> foreach(print, Iterators.cycle(['j', 'u', 'l', 'i', 'a'], 3))
juliajuliajulia

julia> repeat([1,2,3], 4) == collect(Iterators.cycle([1,2,3], 4))
true

julia> fill([1,2,3], 4) == collect(Iterators.repeated([1,2,3], 4))
true
source
Base.Iterators.repeatedFunction
repeated(x[, n::Int])

x를 영원히 생성하는 반복자입니다. n이 지정되면, x를 그만큼 생성합니다 (이는 take(repeated(x), n)과 동일합니다).

또한 fillIterators.cycle와 비교하십시오.

예제

julia> a = Iterators.repeated([1 2], 4);

julia> collect(a)
4-element Vector{Matrix{Int64}}:
 [1 2]
 [1 2]
 [1 2]
 [1 2]

julia> ans == fill([1 2], 4)
true

julia> Iterators.cycle([1 2], 4) |> collect |> println
[1, 2, 1, 2, 1, 2, 1, 2]
source
Base.Iterators.productFunction
product(iters...)

여러 반복자의 곱에 대한 반복기를 반환합니다. 생성된 각 요소는 i번째 요소가 i번째 인수 반복자에서 오는 튜플입니다. 첫 번째 반복자가 가장 빠르게 변경됩니다.

참고: zip, Iterators.flatten.

예제

julia> collect(Iterators.product(1:2, 3:5))
2×3 Matrix{Tuple{Int64, Int64}}:
 (1, 3)  (1, 4)  (1, 5)
 (2, 3)  (2, 4)  (2, 5)

julia> ans == [(x,y) for x in 1:2, y in 3:5]  # Iterators.product을 포함하는 생성기를 수집합니다.
true
source
Base.Iterators.flattenFunction
flatten(iter)

주어진 반복자가 반복자를 생성하는 경우, 해당 반복자의 요소를 생성하는 반복자를 반환합니다. 다시 말해, 인수 반복자의 요소가 연결됩니다.

예제

julia> collect(Iterators.flatten((1:2, 8:9)))
4-element Vector{Int64}:
 1
 2
 8
 9

julia> [(x,y) for x in 0:1 for y in 'a':'c']  # Iterators.flatten을 포함하는 생성기를 수집합니다.
6-element Vector{Tuple{Int64, Char}}:
 (0, 'a')
 (0, 'b')
 (0, 'c')
 (1, 'a')
 (1, 'b')
 (1, 'c')
source
Base.Iterators.flatmapFunction
Iterators.flatmap(f, iterators...)

flatten(map(f, iterators...))와 동일합니다.

자세한 내용은 Iterators.flatten, Iterators.map를 참조하세요.

Julia 1.9

이 함수는 Julia 1.9에 추가되었습니다.

예제

julia> Iterators.flatmap(n -> -n:2:n, 1:3) |> collect
9-element Vector{Int64}:
 -1
  1
 -2
  0
  2
 -3
 -1
  1
  3

julia> stack(n -> -n:2:n, 1:3)
ERROR: DimensionMismatch: stack expects uniform slices, got axes(x) == (1:3,) while first had (1:2,)
[...]

julia> Iterators.flatmap(n -> (-n, 10n), 1:2) |> collect
4-element Vector{Int64}:
 -1
 10
 -2
 20

julia> ans == vec(stack(n -> (-n, 10n), 1:2))
true
source
Base.Iterators.partitionFunction
partition(collection, n)

컬렉션을 n 요소씩 반복합니다.

예제

julia> collect(Iterators.partition([1,2,3,4,5], 2))
3-element Vector{SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}}:
 [1, 2]
 [3, 4]
 [5]
source
Base.Iterators.mapFunction
Iterators.map(f, iterators...)

지연 매핑을 생성합니다. 이는 (f(args...) for args in zip(iterators...))를 작성하는 또 다른 구문입니다.

Julia 1.6

이 함수는 최소한 Julia 1.6이 필요합니다.

예제

julia> collect(Iterators.map(x -> x^2, 1:3))
3-element Vector{Int64}:
 1
 4
 9
source
Base.Iterators.filterFunction
Iterators.filter(flt, itr)

주어진 술어 함수 flt와 반복 가능한 객체 itr에 대해, flt(x)를 만족하는 itr의 요소 x를 반복할 때 생성하는 반복 가능한 객체를 반환합니다. 원래 반복자의 순서는 유지됩니다.

이 함수는 지연 방식입니다; 즉, $Θ(1)$ 시간에 반환되고 $Θ(1)$의 추가 공간을 사용하며, filter의 호출로 flt가 호출되지 않을 것임이 보장됩니다. 반환된 반복 가능한 객체를 반복할 때 flt에 대한 호출이 이루어집니다. 이러한 호출은 캐시되지 않으며, 반복할 때마다 반복 호출이 이루어집니다.

!!! 경고 filter에서 반환된 반복자에 대한 후속 지연 변환, 예를 들어 Iterators.reversecycle에 의해 수행되는 변환은 반환된 반복 가능한 객체를 수집하거나 반복할 때까지 flt에 대한 호출을 지연시킵니다. 필터 술어가 비결정적이거나 반환 값이 itr의 요소에 대한 반복 순서에 따라 달라지는 경우, 지연 변환과의 조합은 놀라운 동작을 초래할 수 있습니다. 이것이 바람직하지 않다면, flt가 순수 함수인지 확인하거나 추가 변환 전에 중간 filter 반복자를 수집하십시오.

배열에 대한 필터링의 즉각적인 구현에 대해서는 Base.filter를 참조하십시오.

예제

julia> f = Iterators.filter(isodd, [1, 2, 3, 4, 5])
Base.Iterators.Filter{typeof(isodd), Vector{Int64}}(isodd, [1, 2, 3, 4, 5])

julia> foreach(println, f)
1
3
5

julia> [x for x in [1, 2, 3, 4, 5] if isodd(x)]  # Iterators.filter를 통해 생성기를 수집합니다.
3-element Vector{Int64}:
 1
 3
 5
source
Base.Iterators.accumulateFunction
Iterators.accumulate(f, itr; [init])

2개의 인자를 가지는 함수 f와 반복자 itr가 주어지면, 이전 값과 itr의 다음 요소에 f를 차례로 적용하는 새로운 반복자를 반환합니다.

이는 사실상 Base.accumulate의 지연 버전입니다.

Julia 1.5

키워드 인자 init은 Julia 1.5에서 추가되었습니다.

예제

julia> a = Iterators.accumulate(+, [1,2,3,4]);

julia> foreach(println, a)
1
3
6
10

julia> b = Iterators.accumulate(/, (2, 5, 2, 5); init = 100);

julia> collect(b)
4-element Vector{Float64}:
 50.0
 10.0
  5.0
  1.0
source
Base.Iterators.reverseFunction
Iterators.reverse(itr)

주어진 반복자 itr에 대해, reverse(itr)는 동일한 컬렉션에 대한 반복자이지만 역순으로 되어 있습니다. 이 반복자는 "지연(lazy)" 방식으로 작동하여 컬렉션을 복사하지 않고 역순으로 만듭니다; 즉, 열심히 구현된 Base.reverse를 참조하십시오.

(기본적으로, 이것은 itr을 감싸는 Iterators.Reverse 객체를 반환하며, 해당 iterate 메서드가 정의되어 있으면 반복할 수 있지만, 일부 itr 유형은 더 특수화된 Iterators.reverse 동작을 구현할 수 있습니다.)

모든 반복자 유형 T가 역순 반복을 지원하는 것은 아닙니다. 만약 T가 지원하지 않는다면, Iterators.reverse(itr::T)를 반복하면 MethodError가 발생합니다. 이는 Iterators.Reverse{T}에 대한 iterate 메서드가 누락되었기 때문입니다. (이 메서드를 구현하기 위해, 원래 반복자 itr::Tr::Iterators.Reverse{T} 객체에서 r.itr로 얻을 수 있습니다; 더 일반적으로, Iterators.reverse(r)를 사용할 수 있습니다.)

예제

julia> foreach(println, Iterators.reverse(1:5))
5
4
3
2
1
source
Base.Iterators.onlyFunction
only(x)

컬렉션 x의 유일한 요소를 반환하거나, 컬렉션에 요소가 0개 또는 여러 개 있을 경우 ArgumentError를 발생시킵니다.

또한 first, last를 참조하세요.

Julia 1.4

이 메서드는 최소한 Julia 1.4가 필요합니다.

예제

julia> only(["a"])
"a"

julia> only("a")
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

julia> only(())
ERROR: ArgumentError: Tuple contains 0 elements, must contain exactly 1 element
Stacktrace:
[...]

julia> only(('a', 'b'))
ERROR: ArgumentError: Tuple contains 2 elements, must contain exactly 1 element
Stacktrace:
[...]
source
Base.Iterators.peelFunction
peel(iter)

첫 번째 요소와 나머지 요소에 대한 반복자를 반환합니다.

반복자가 비어 있으면 nothing을 반환합니다 (예: iterate와 같음).

Julia 1.7

이전 버전에서는 반복자가 비어 있을 경우 BoundsError를 발생시킵니다.

참고: Iterators.drop, Iterators.take.

예제

julia> (a, rest) = Iterators.peel("abc");

julia> a
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

julia> collect(rest)
2-element Vector{Char}:
 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
source