Hi !
Is there a way to use a a comparison operator (>, <, ==…) as a function argument ?
for example
f(2,5,>=)
function compare(x,y, operator)::Bool
return x operator y # 2>=5, return false
Thanks !
Hi !
Is there a way to use a a comparison operator (>, <, ==…) as a function argument ?
for example
f(2,5,>=)
function compare(x,y, operator)::Bool
return x operator y # 2>=5, return false
Thanks !
The trick here is to remember that any operator can be rewritten as a function call with parentheses.
So
f(a, b, operator) = operator(a,b)
f(1,2, >)
# false
f(2,2, ==)
# true
Those are normal functions as well so you can do it like this:
julia> compare(f,x,y) = f(x,y)
compare (generic function with 1 method)
julia> compare(>=,2,5)
false
but this seems mostly not necessary. You could just as well use map(f,x,y)
which already exists.
@mrufsvold , @tbeason very interesting ! Thanks !