Skip to content

Commit

Permalink
Add Base.reduce
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Aug 2, 2019
1 parent e1a3093 commit ffe9c31
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
1 change: 1 addition & 0 deletions docs/src/manual.md
Expand Up @@ -13,6 +13,7 @@ transduce
foldl
foreach
mapreduce
reduce
eduction
map!
copy!
Expand Down
24 changes: 12 additions & 12 deletions examples/words.jl
Expand Up @@ -164,30 +164,30 @@ countxf = wordsxf |> Map(processcount)
# function `mergecont!`:

mergecont!(a, b) = merge!(+, a, b)
mergecont!(a) = a
nothing # hide

# Note that the unary form is required for the completion.
# Alternatively, we can use [`Completing((a, b) -> merge!(+, a,
# b))`](@ref Completing) instead of `mergecont!`. Putting the
# transducer and reducing function together, we get:
# Putting the transducer and reducing function together, we get:

countwords(s; kwargs...) =
mapreduce(Map(Char) |> countxf,
mergecont!,
transcode(UInt8, s);
init = CopyInit(Dict{String,Int}()),
kwargs...)
reduce(mergecont!,
Map(Char) |> countxf,
transcode(UInt8, s);
init = CopyInit(Dict{String,Int}()),
kwargs...)
nothing # hide

# Side note: Since [`mapreduce`](@ref) does not support string, the
# input string is converted to a `Vector{UInt8}` first by `transcode`.
# Side note: Since [`reduce`](@ref) does not support string, the input
# string is converted to a `Vector{UInt8}` first by `transcode`.
# That's why there is `Map(Char) |>` before `countxf`. Of course,
# this is not valid for UTF-8 in general.
#
# Side note 2: We use [`CopyInit`](@ref) to create a fresh initial
# state for each sub-reduce to avoid overwriting mutable data between
# threads.
#
# Side note 3: [`reduce`](@ref) wraps `mergecont!` automatically with
# [`Completing`](@ref). This is why `mergecont!` does not have to
# have the unary method.

# Let's run some tests with different `basesize` (`length(s) /
# basesize` corresponds to number of tasks to be used):
Expand Down
11 changes: 11 additions & 0 deletions src/processes.jl
Expand Up @@ -385,6 +385,14 @@ See [`mapfoldl`](@ref).
"""
Base.mapreduce

"""
reduce(step, xf, reducible; init, simd)
Like [`mapreduce`](@ref) but `step` is automatically wrapped by
[`Completing`](@ref).
"""
Base.reduce

@static if VERSION >= v"1.3-alpha"
function __reduce__(
rf, init, arr::AbstractArray;
Expand Down Expand Up @@ -445,6 +453,9 @@ function Base.mapreduce(xform::Transducer, step, itr::AbstractArray;
return unreduced(complete(rf, __reduce__(rf, init, itr; kwargs...)))
end

Base.reduce(step, xform::Transducer, itr; kwargs...) =
mapreduce(xform, Completing(step), itr; kwargs...)

struct Eduction{F, C}
rf::F
coll::C
Expand Down

0 comments on commit ffe9c31

Please sign in to comment.