Skip to content

Commit

Permalink
leave a minimal implementation of passmissing
Browse files Browse the repository at this point in the history
  • Loading branch information
bkamins committed Aug 31, 2018
1 parent 1516580 commit 3bf10c0
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 31 deletions.
33 changes: 5 additions & 28 deletions src/Missings.jl
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
module Missings

export allowmissing, disallowmissing, ismissing, missing, missings,
Missing, MissingException, levels, coalesce,
conditional, passmissing
Missing, MissingException, levels, coalesce, passmissing

using Base: ismissing, missing, Missing, MissingException

Expand Down Expand Up @@ -166,32 +165,10 @@ function levels(x)
levs
end

struct Conditional{P,X,Y} <: Function end
struct PassMissing{F} <: Function end

"""
conditional(predicate, x, y)
Return a function that that applies function `predicate` to its positional and keyword
arguments and returns the value of `x` applied to those arguments if `predicate`
returns true and otherwise returns the value of `y` applied to those arguments.
# Examples
```jldoctest
julia> f = conditional(x -> x ≥ 0, sqrt, x -> sqrt(complex(x)));
julia> f.([4, -4])
2-element Array{Number,1}:
2.0
0.0 + 2.0im
"""
conditional(predicate::Function, x::Base.Callable, y::Base.Callable) =
Conditional{predicate, x, y}()
(::Conditional{P,X,Y})(xs...;kw...) where {P,X,Y} =
P(xs...; kw...) ? X(xs...; kw...) : Y(xs...; kw...)

_passmissing_predicate(xs...;kw...) =
any(ismissing.(xs)) || any(ismissing.(values(values(kw))))
_passmissing_value(xs...;kw...) = missing
(::PassMissing{F})(xs...;kw...) where {F} =
any(ismissing, xs) || any(ismissing, values(values(kw))) ? missing : F(xs...; kw...)

"""
passmissing(f)
Expand All @@ -206,6 +183,6 @@ julia> passmissing(sqrt).([missing, 4])
missing
2.0
"""
passmissing(f) = conditional(_passmissing_predicate, _passmissing_value, f)
passmissing(f::Base.Callable) = PassMissing{f}()

end # module
4 changes: 1 addition & 3 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -357,8 +357,6 @@ using Test, Dates, InteractiveUtils, SparseArrays, Missings
@test sprint(showerror, MissingException("test")) == "MissingException: test"

# Lifting
fun1 = conditional(x -> x 0, sqrt, x -> sqrt(complex(x)));
@test fun1(4) === 2.0
@test fun1(-4) === 2.0im
@test isequal(passmissing(sqrt).([missing, 4]), [missing, 2.0])
@test isequal(passmissing(parse)(Int, "a", base=missing), missing)
end

0 comments on commit 3bf10c0

Please sign in to comment.