A comparison operator (>, <, ==...) as a function argument?

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
3 Likes

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.

3 Likes

@mrufsvold , @tbeason very interesting ! Thanks !