Is there a way to block type conversion?

I’m writing some simple functions with combinatorial flavor (derived from IBM’s research language FL), but they cannot be used as needed by the intrusive type conversion.

Example:

julia> DISTL([100,[10.,20.,30.]])       # distribute left
3-element Vector{Vector{Float64}}:
 [100.0, 10.0]
 [100.0, 20.0]
 [100.0, 30.0]

while I need

julia> DISTL([100,[10.,20.,30.]])
3-element Vector{Vector{Any}}:
 [100, 10.0]
 [100, 20.0]
 [100, 30.0]

Could you share with us your mplementation of DISTL?

Julia itself does not appear to be doing type conversion of the input.

julia> [100,[10.,20.,30.]]
2-element Vector{Any}:
 100
    [10.0, 20.0, 30.0]

I might implement DISTL as follows to get a similar result.

julia> DISTL(input) = vcat.(input[1], input[2])
DISTL (generic function with 1 method)

julia> DISTL([100, [10., 20., 30.]])          3-element Vector{Vector{Float64}}:
 [100.0, 10.0]
 [100.0, 20.0]
 [100.0, 30.0]

Fixing it would look as follows.

julia> DISTL(input) = Base.typed_vcat.((Number,), input[1], input[2])
DISTL (generic function with 1 method)

julia> DISTL([100, [10., 20., 30.]])          
3-element Vector{Vector{Number}}:
 [100, 10.0]
 [100, 20.0]
 [100, 30.0]
function DISTL(args)
	Element, List = args
	return [[Element, e] for e in List]
end

How about specifying the element type you want?

function DISTL(args)
	Element, List = args
	return [Any[Element, e] for e in List]
end

You don’t have to specify a known type, you can do it generically, even make it an argument

function DISTL(args, T) # 2nd method
	Element, List = args
	return [T[Element, e] for e in List]
end

I was going to suggest

julia> function DISTL(args)
           Element, List = args
           return [Number[Element, e] for e in List]
       end
DISTL (generic function with 1 method)

julia> DISTL([100, [10., 20., 30.]])
3-element Vector{Vector{Number}}:
 [100, 10.0]                                 
 [100, 20.0]
 [100, 30.0]

Here’s another version that creates a type Union.

julia> function DISTL(args)
           Element, List = args
           T = Union{typeof(Element), eltype(List)}
           return [T[Element, e] for e in List]
       end
DISTL (generic function with 1 method)

julia> DISTL([100, [10., 20., 30.]])
3-element Vector{Vector{Union{Float64, Int64}}}:                               
 [100, 10.0]
 [100, 20.0]                                 
 [100, 30.0]
1 Like

This is OK, because one needed characteristic is to work with “any” kind of object
Thank you !!

THIS looks very OK. Thank you !!

julia> DISTL(["100", [10., 20., 30.]])
3-element Vector{Vector{Union{Float64, String}}}:
 ["100", 10.0]
 ["100", 20.0]
 ["100", 30.0]