Skip to content

Commit dd18e84

Browse files
committed
Re-add composition with and new compose function
1 parent 1495e75 commit dd18e84

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

docs/src/operations.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ There are two functions that take a `Bijection` and return a new
1212
Given a `Bijection` `b`, calling `inv(b)` creates a new `Bijection`
1313
that is the inverse of `b`. The new `Bijection` is completely independent
1414
of the original, `b`. Changes to one do not affect the other:
15+
1516
```
1617
julia> b = Bijection{Int,String}()
1718
Bijection Dict{Int64, String}()
@@ -80,3 +81,15 @@ julia> for (x,y) in b; println("$x --> $y"); end
8081
1 --> alpha
8182
```
8283

84+
## Composition
85+
86+
Given two `Bijection`s `a` and `b`, their composition `c = a ∘ b` or `c = compose(a, b)` is a new `Bijection` with the property that `c[x] = a[b[x]]` for all `x` in the
87+
domain of `b`.
88+
89+
```
90+
julia> a = Bijection{Int,Int}(1 => 10, 2 => 20);
91+
julia> b = Bijection{String,Int}("hi" => 1, "bye" => 2);
92+
julia> c = a ∘ b;
93+
julia> c["hi"]
94+
10
95+
```

src/Bijections.jl

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ module Bijections
22

33
using Serialization: Serialization
44

5-
export Bijection, active_inv, inverse, hasvalue
5+
export Bijection, active_inv, inverse, hasvalue, compose
66

77
struct Bijection{K,V,F,Finv} <: AbstractDict{K,V}
88
f::F # map from domain to range
@@ -269,4 +269,21 @@ function Serialization.deserialize(
269269
return B(f)
270270
end
271271

272+
"""
273+
c = (∘)(a::Bijection{A,B}, b::Bijection{B,C})::Bijection{A,C} where {A,B,C}
274+
c = compose(a, b)
275+
276+
The result of `a ∘ b` or `compose(a, b)` is a new `Bijection` `c` such that
277+
`c[x]` is `a[b[x]]` for `x` in the domain of `b`.
278+
"""
279+
function compose(a::Bijection{B,A}, b::Bijection{C,B}) where {A,B,C}
280+
c = Bijection{C,A}()
281+
for x in keys(b)
282+
c[x] = a[b[x]]
283+
end
284+
return c
285+
end
286+
287+
Base.:()(a::Bijection, b::Bijection) = compose(a, b)
288+
272289
end # end of module Bijections

test/runtests.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,22 @@ using Serialization
3838
@test Bijection(collect(b)) == b
3939
end
4040

41+
# check composition
42+
@testset "Composition" begin
43+
a = Bijection{Int,Int}()
44+
a[1] = 10
45+
a[2] = 20
46+
47+
b = Bijection{String,Int}()
48+
b["hi"] = 1
49+
b["bye"] = 2
50+
51+
c = a b
52+
@test c["hi"] == 10
53+
54+
@test compose(a, b) == c
55+
end
56+
4157
# Test empty constructor
4258
@testset "empty_constructor" begin
4359
b = Bijection{Int,String}()

0 commit comments

Comments
 (0)