Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Try.unwrap_or_else #43

Merged
merged 2 commits into from
Apr 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Try.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ function var"@?" end

function and_then end
function or_else end
function unwrap_or_else end

module Internal

Expand Down
43 changes: 32 additions & 11 deletions src/branch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,6 @@ macro and_return(ex)
end
end

function Try.and_then(f::F) where {F}
function and_then_closure(result)
Try.and_then(f, result)
end
end

function Try.and_then(f, result)
br = branch(result)
if br isa Continue
Expand All @@ -81,17 +75,44 @@ function Try.and_then(f, result)
end
end

function Try.or_else(f::F) where {F}
function or_else_closure(result)
Try.or_else(f, result)
function Try.or_else(f, result)
br = branch(result)
if br isa Break
f(valueof(br))
else
br.result
end
end

function Try.or_else(f, result)
function Try.unwrap_or_else(f, result)
br = branch(result)
if br isa Break
f(valueof(br))
else
br.result
valueof(br)
end
end

###
### Currying
###

# TODO: Automate currying?

function Try.and_then(f::F) where {F}
function and_then_closure(result)
Try.and_then(f, result)
end
end

function Try.or_else(f::F) where {F}
function or_else_closure(result)
Try.or_else(f, result)
end
end

function Try.unwrap_or_else(f::F) where {F}
function unwrap_or_else(result)
Try.unwrap_or_else(f, result)
end
end
15 changes: 15 additions & 0 deletions src/docs/unwrap_or_else.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Try.unwrap_or_else(_, Ok(value)) -> value
Try.unwrap_or_else(f, Err(x)) -> f(x)

Unwrap an [`Ok`](@ref) value or compute a result from the value wrapped in [`Err`](@ref).

# Examples
```julia
julia> using Try

julia> Try.unwrap_or_else(length, Try.Ok(1))
1

julia> Try.unwrap_or_else(length, Try.Err("four"))
4
```
5 changes: 5 additions & 0 deletions test/TryTests/src/test_tools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ function test_or_return()
@test Try.unwrap(try_map_prealloc2(x -> x + 1, 1:3)) == 2:4
end

function test_unwrap_or_else()
@test Try.unwrap_or_else(length, Try.Ok(1)) == 1
@test Try.unwrap_or_else(length, Try.Err("four")) == 4
end

function test_curry()
value =
tryconvert(String, 1) |>
Expand Down