Home > Software engineering >  Julia: sortslices: is it possible to pass the sort logic as a variable rather than a literal?
Julia: sortslices: is it possible to pass the sort logic as a variable rather than a literal?

Time:02-22

unsorted = [3 5 9; 3 -6 11; 2 -4 8; 2 7 10]
sorted_1 = sortslices(unsorted, dims=1, by=x->(x[1],-abs(x[2])) )

gives as expected:

4×3 Array{Int64,2}:
 2   7  10
 2  -4   8
 3  -6  11
 3   5   9

I tried to put the third argument into a variable and pass it:

unsorted    = [3 5 9; 3 -6 11; 2 -4 8; 2 7 10]
sort_string = "by=x->(x[1],-abs(x[2]))"
sorted_2    = sortslices(output, dims=1, sort_string) 

which gives:

ERROR: LoadError: MethodError: no method matching sortslices(::Array{Float64,2}, ::String; dims=1)
Closest candidates are:
  sortslices(::AbstractArray; dims, kws...) at multidimensional.jl:1751

Is there a syntax tweak that makes this work, or is there no solution like that?

(The reason I am trying to do this is that the sort logic I am coding depends on multiple user inputs, some of which are not binary. I can do nested ifs to give 2 * 3 * 4 combinations each having a sortslices call, but it would be neater to concatenate the sort logic as a string which would involve only 2 3 4 if lines)

P.S. I am using Julia 1.5.3

CodePudding user response:

You can use metaprogramming:

julia> sort_string = "x->(x[1],-abs(x[2]))";

julia> sorted_2 = sortslices(unsorted, dims=1, by=Meta.eval(Meta.parse(sort_string)))
4×3 Matrix{Int64}:
 2   7  10
 2  -4   8
 3  -6  11
 3   5   9
  • Related