Skip to content

Commit

Permalink
Merge pull request #17155 from JuliaLang/sk/funcnegcomp
Browse files Browse the repository at this point in the history
function composition (f∘g) and negation (!f)
  • Loading branch information
StefanKarpinski authored Jan 4, 2017
2 parents 7bb7f13 + ab6f431 commit 887815c
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 1 deletion.
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ export
~,
:,
=>,
,
A_ldiv_B!,
A_ldiv_Bc,
A_ldiv_Bt,
Expand Down
45 changes: 44 additions & 1 deletion base/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,48 @@ julia> [1:5;] |> x->x.^2 |> sum |> inv
"""
|>(x, f) = f(x)

# function composition

"""
f ∘ g
Compose functions: i.e. `(f ∘ g)(args...)` means `f(g(args...))`. The `∘` symbol can be
entered in the Julia REPL (and most editors, appropriately configured) by typing `\circ<tab>`.
Example:
```jldoctest
julia> map(uppercase∘hex, 250:255)
6-element Array{String,1}:
"FA"
"FB"
"FC"
"FD"
"FE"
"FF"
```
"""
(f, g) = (x...)->f(g(x...))


"""
!f::Function
Predicate function negation: when the argument of `!` is a function, it returns a
function which computes the boolean negation of `f`. Example:
```jldoctest
julia> str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"
"∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"
julia> filter(isalpha, str)
"εδxyδfxfyε"
julia> filter(!isalpha, str)
"∀ > 0, ∃ > 0: |-| < ⇒ |()-()| < "
```
"""
!(f::Function) = (x...)->!f(x...)

# array shape rules

promote_shape(::Tuple{}, ::Tuple{}) = ()
Expand Down Expand Up @@ -989,6 +1031,7 @@ export
,
,
,
,
colon,
hcat,
vcat,
Expand All @@ -1002,6 +1045,6 @@ import ..this_module: !, !=, xor, %, ÷, &, *, +, -,
/, //, <, <:, <<, <=, ==, >, >=, >>, >>>,
<|, |>, \, ^, |, ~, !==, ===, >:, colon, hcat, vcat, hvcat, getindex, setindex!,
transpose, ctranspose,
, , , , ×, , , , , , , , , , , ,
, , , , ×, , , , , , , , , , , , ,

end
1 change: 1 addition & 0 deletions doc/src/stdlib/base.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ Base.method_exists
Core.applicable
Core.invoke
Base.:(|>)
Base.:(∘)
```

## Syntax
Expand Down
10 changes: 10 additions & 0 deletions test/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,13 @@ Base.:/(::T19714, ::T19714) = T19714()
Base.convert(::Type{T19714}, ::Int) = T19714()
Base.promote_rule(::Type{T19714}, ::Type{Int}) = T19714
@test T19714()/1 === 1/T19714() === T19714()

# pr #17155
@testset "function composition" begin
@test (uppercasehex)(239487) == "3A77F"
end
@testset "function negation" begin
str = randstring(20)
@test filter(!isupper, str) == replace(str, r"[A-Z]", "")
@test filter(!islower, str) == replace(str, r"[a-z]", "")
end

0 comments on commit 887815c

Please sign in to comment.