Home > Software engineering >  Allow outer variable inside Julia's sort comparison
Allow outer variable inside Julia's sort comparison

Time:04-24

The issue:

I want to be able to sort with a custom function that depends on an outer defined variable, for example:

k = 2
sort([1,2,3], lt=(x,y) -> x   k > y)

This works all dandy and such because k is defined in the global scope.

That's where my issue lays, as I want to do something akin to:

function 
    k = 2
    comp = (x,y) -> x   k > y
    sort([1,3,3], lt=comp)
end

Which works, but feels like a hack, because my comparison function is way bigger and it feels really off to have to have it defined there in the body of the function.

For instance, this wouldn't work:

comp = (x,y) -> x   k > y # or function comp(x,y) ... end
function 
    k = 2
    sort([1,3,3], lt=comp)
end

So I'm just wondering if there's any way to capture variables such as k like you'd be able to do with lambda functions in C .

CodePudding user response:

Is this what you want?

julia> comp(k) = (x,y) -> x   k > y
comp (generic function with 1 method)

julia> sort([1,3,2,3,2,2,2,3], lt=comp(2))
8-element Vector{Int64}:
 3
 2
 2
 2
 3
 2
 3
 1
  • Related