Skip to content

Commit

Permalink
Create @something
Browse files Browse the repository at this point in the history
  • Loading branch information
omus committed May 6, 2021
1 parent f806df6 commit 3773a14
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,7 @@ export
ismissing,
missing,
skipmissing,
@something,
something,
isnothing,
nonmissingtype,
Expand Down
38 changes: 38 additions & 0 deletions base/some.jl
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,41 @@ something() = throw(ArgumentError("No value arguments present"))
something(x::Nothing, y...) = something(y...)
something(x::Some, y...) = x.value
something(x::Any, y...) = x


"""
@something(x, y...)
Short-circuiting version of [`something`](@ref something).
# Examples
```jldoctest
julia> f(x) = (println("f(\$x)"); nothing);
julia> a = 1;
julia> a = @something a f(2) f(3) error("Unable to find default for `a`")
1
julia> b = nothing;
julia> b = @something b f(2) f(3) error("Unable to find default for `b`")
f(2)
f(3)
ERROR: Unable to find default for `b`
[...]
julia> b = @something b f(2) f(3) Some(nothing)
f(2)
f(3)
```
"""
macro something(args...)
expr = :(nothing)
for arg in reverse(args)
expr = :((val = $arg) !== nothing ? val : $expr)
end
return esc(:(something(let val; $expr; end)))
end

10 changes: 10 additions & 0 deletions test/some.jl
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@
@test something(missing, nothing, missing) === missing
end

@testset "@something" begin
@test_throws ArgumentError @something()
@test_throws ArgumentError @something(nothing)
@test @something(1) === 1
@test @something(Some(nothing)) === nothing

@test @something(1, error("failed")) === 1
@test_throws ErrorException @something(nothing, error("failed"))
end

# issue #26927
a = [missing, nothing, Some(nothing), Some(missing)]
@test a isa Vector{Union{Missing, Nothing, Some}}
Expand Down

0 comments on commit 3773a14

Please sign in to comment.