Skip to content

Commit 74cbf5d

Browse files
Stephan SahmStephan Sahm
authored andcommitted
added @Either macro
1 parent 838b15a commit 74cbf5d

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

src/DataTypesBasic.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ module DataTypesBasic
3131

3232
export Const, Identity,
3333
Option, issomething, iftrue, iffalse, getOption, # isnothing, Nothing, Some comes from Base
34-
Either, either, isleft, isright, getleft, getright, getleftOption, getrightOption, flip_left_right,
34+
Either, either, @either, isleft, isright, getleft, getright, getleftOption, getrightOption, flip_left_right,
3535
OptionEither,
3636
Try, Thrown, @Try, @TryCatch, issuccess, isexception, MultipleExceptions,
3737
ContextManager, @ContextManager

src/Either.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,26 @@ function either(left_false, comparison::Bool, right_true)
1616
comparison ? Identity(right_true) : Const(left_false)
1717
end
1818

19+
"""
20+
@either true ? "right" : Symbol("left")
21+
@either if false
22+
"right"
23+
else
24+
:left
25+
end
26+
27+
Simple macro to reuse ? operator and simple if-else for constructing Either.
28+
"""
29+
macro either(expr::Expr)
30+
@assert expr.head == :if && length(expr.args) == 3 "@either macro only works on ? or simple if-else."
31+
if isa(expr.args[3], Expr) && (expr.args[3].head == :elseif)
32+
error("Found elseif, however can only deal with simple if-else.")
33+
end
34+
esc(quote
35+
DataTypesBasic.either($(expr.args[3]), $(expr.args[1]), $(expr.args[2]))
36+
end)
37+
end
38+
1939
flip_left_right(x::Const) = Identity(x.value)
2040
flip_left_right(x::Identity) = Const(x.value)
2141

0 commit comments

Comments
 (0)