Clarification:
I’m looking for something similar to: condition ? a : b
Except, my condition is when a returns some type of error, then do b instead of a.
No such function can ever exist in general because functions evaluate all of their arguments, but you want control flow (like the ternary operator provides), so you need to write a macro. Maybe something like the following:
macro trycatch(a, b)
quote
try
tmp = $(esc(a))
tmp
catch
$(esc(b))
end
end
end
let x = 2
@trycatch(sqrt(x), sqrt(complex(x)))
end
let x = -2
@trycatch(sqrt(x), sqrt(complex(x)))
end
What do you mean by that? That’s part of Julia’s syntax: it’s in the parser and isn’t a function whose definition you could read. You could write a macro to reuse that syntax for your own needs if you wanted to.
Functions are very different from macros. You can redefine infix operators, because they are just generic functions. Functions can’t transform syntax though. For example, you can define the infix operator $:
julia> a $ b = 10 * a + b
$ (generic function with 1 method)
julia> 1 $ 2
12
I think you’re getting fixated on macro being an infix operator, which isn’t possible but shouldn’t matter that much. You can easily do something like @t a $ b.