Skip to content

Commit

Permalink
Add new API: adjoininit
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed May 24, 2020
1 parent d64c3ac commit 1aa3b19
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
48 changes: 41 additions & 7 deletions src/InitialValues.jl
Expand Up @@ -6,7 +6,7 @@ module InitialValues
replace(read(path, String), r"^```julia"m => "```jldoctest README")
end InitialValues

export INIT, Init, SomeInit, asmonoid, initialize
export INIT, Init, SomeInit, adjoininit, asmonoid, initialize

"""
Init(op) :: InitialValue
Expand Down Expand Up @@ -424,21 +424,18 @@ julia> using InitialValues
julia> asmonoid(*) === * # do nothing if `Init` is already defined
true
julia> append!′ = asmonoid(append!);
julia> vcat′ = asmonoid(vcat);
julia> xs = [];
julia> append!′(Init(append!′), xs) === xs
julia> vcat′(Init(vcat′), xs) === xs
true
julia> foldl(append!′, [xs, [1], [2, 3]], init=Init(append!′))
julia> foldl(vcat′, [xs, [1], [2, 3]], init=Init(vcat′))
3-element Array{Any,1}:
1
2
3
julia> ans === xs # `xs` is modified
true
```
"""
asmonoid(op) = hasinitialvalue(op) ? op : AdjoinIdentity(op)
Expand All @@ -452,4 +449,41 @@ asmonoid(op) = hasinitialvalue(op) ? op : AdjoinIdentity(op)
x::SpecificInitialValue{AdjoinIdentity{OP}}) where OP = x
hasinitialvalue(::Type{AdjoinIdentity{T}}) where {T} = true

"""
adjoininit(op) -> op′
Transform a binary function `op` to a function `op′` such that
`hasinitialvalue(op′) === true`. Do nothing if `op` already has a
known initial value.
This is equivalent to [`asmonoid`](@ref) by default. Frameworks for
composing `op` (e.g., Transducers.jl) may overload this function such
that `op′` itself is not a monoid.
# Examples
```jldoctest
julia> using InitialValues
julia> adjoininit(*) === * # do nothing if `Init` is already defined
true
julia> append!′ = adjoininit(append!);
julia> xs = [];
julia> append!′(Init(append!′), xs) === xs
true
julia> foldl(append!′, [xs, [1], [2, 3]], init=Init(append!′))
3-element Array{Any,1}:
1
2
3
julia> ans === xs # `xs` is modified
true
```
"""
adjoininit(op) = asmonoid(op)

end # module
5 changes: 4 additions & 1 deletion test/test_basics.jl
Expand Up @@ -114,7 +114,10 @@ end
@test hasinitialvalue(typeof(absmin))
@test isknown(Init(absmin))

@test asmonoid(+) === +
@test asmonoid(absmin) === absmin
@test adjoininit(absmin.op) === adjoininit(absmin) === absmin
@test asmonoid(nothing) === adjoininit(nothing) !== nothing
@test asmonoid(+) === adjoininit(+) === +
end

@testset "initialize" begin
Expand Down

0 comments on commit 1aa3b19

Please sign in to comment.