Julia – Passing two arguments to make array, iterate through first argument but not second

I am new to Julia and would be very appreciative of your help. I have a function that takes an integer and an array of integers, which will return an integer. I want to make an array of the results of this function over a range. However, I am struggling to get Julia to recognise that it needs to iterate over the array parsed in the first argument in place of the integer, and to not iterate over the second. Below is an example.

function example(x::Int, y::Array{Int})
    a = get_random_number_from_y(y)
    return x + a
end

range = 1:20
y = 1:1000

results = example.(range, y)

When I run this code, I get the following:

ERROR: LoadError: DimensionMismatch("arrays could not be broadcast to a common size; got a dimension with lengths 20 and 1000")

Is there any way to do this?

>Solution :

There are two main issues in your code.

  1. The second argument is restricted to Array{Int}, but you give the function a UnitRange as second argument y = 1:1000 instead.
  2. To broadcast properly, you should have a whole array object as second argument for each scalar from first argument.

To remedy 1, change the function signature to a more-generic Array type that includes ranges. example(x::Int, y::AbstractArray{Int}) is what you’re looking for. You could leave out the types altogether like example(x, y) unless you really mean to restrict inputs or for documentation purposes.

To remedy 2, make the second argument y an iterable of array objects instead of a single object (array). Turn y into a tuple (y,) to achieve that.

Note that variable names like range are not recommended as their is a function in Base called range, better to choose a different descriptive name like _range to avoid confusing your self and the readers of your code.

function example(x::Int, y::AbstractArray{Int})
    a = y[1]
    return x + a
end

_range = 1:20
y = 1:1000

results = example.(_range, (y,))

Leave a Reply