@permute_args macro helps define functions with permutable arguments and structs with permutable fields. No runtime overhead.
using Pkg; Pkg.add("PermuteArgs")
using PermuteArgs
@permute_args test_func(x::Int, y::String) = "x=$x, y=$y"
test_func(42, "hello") == test_func("hello", 42) == "x=42, y=hello"
@permute_args struct TestStruct
x::Int
y::String
end
TestStruct(42, "hello") == TestStruct("hello", 42)lazy replaces the n! permuted methods with one Vararg{Union{...}} dispatcher, compiling each
argument order on first call instead. Same runtime; worth it from ~5 arguments up.
@permute_args lazy function big(a::Int, b::Float64, c::String, d::Char, e::Bool, f::UInt8)
return (a, b, c, d, e, f)
endDefinition plus one call:
| n | eager | lazy |
|---|---|---|
| 5 | 120 methods, 31 ms | 2 methods, 11 ms |
| 6 | 720 methods, 199 ms | 2 methods, 12 ms |
| 7 | 5040 methods, 1531 ms | 2 methods, 12 ms |
test(x::Int, y::String) = "x=$x, y=$y"
permuted_test = permute_args(test, [Int, String])
permuted_test(42, "hello") == permuted_test("hello", 42)Type arguments can be omitted and the first method of the function will be used instead.
permuted_func = permute_args(base_func)permute_args!(test, [Int, String])
test(42, "hello") == test("hello", 42)