Not sue if this is exactly what you want, but you can achieve this with
`map!` by making `add_one!` return the modified MyType:
julia> type MyType; x::Int; end
julia> function add_one!(mt::MyType)
mt.x += 1
return mt
end
add_one! (generic function with 1 method)
julia> A = map(MyType, 1:3)
3-element Array{MyType,1}:
MyType(1)
MyType(2)
MyType(3)
julia> map!(add_one!, A)
3-element Array{MyType,1}:
MyType(2)
MyType(3)
MyType(4)
julia> A
3-element Array{MyType,1}:
MyType(2)
MyType(3)
MyType(4)
On Tuesday, 9 June 2015 20:39:11 UTC+1, Tom Breloff wrote:
>
> I'm probably overlooking something simple, but is there a built-in
> function to "apply" a function to each element of an abstract array without
> creating a new array? This obviously only makes sense when you're updating
> an object as part of the function call. Here's an example below... does
> this exist in Base? Should it?
>
>
> julia> function map_without_result(f, A)
> for x in A
> f(x)
> end
> end
> map_without_result (generic function with 1 method)
>
> julia> type MyType; x::Int; end
>
> julia> add_one!(mt::MyType) = mt.x += 1
> add_one! (generic function with 1 method)
>
> julia> A = map(MyType, 1:5)
> 10-element Array{MyType,1}:
> MyType(1)
> MyType(2)
> MyType(3)
> MyType(4)
> MyType(5)
>
> julia> map_without_result(add_one!, A)
>
> julia> A
> 10-element Array{MyType,1}:
> MyType(2)
> MyType(3)
> MyType(4)
> MyType(5)
> MyType(6)
>
>
>
> Currently (on master from 5 days ago), "map(add_one!, A)" will return a
> new Vector{Int}, and "map!(add_one!, A)" gives an error:
>
>
> julia> map(add_one!, A)
> 5-element Array{Int64,1}:
> 3
> 4
> 5
> 6
> 7
>
> julia> map!(add_one!, A)
> ERROR: MethodError: `convert` has no method matching
> convert(::Type{MyType}, ::Int64)
> This may have arisen from a call to the constructor MyType(...),
> since type constructors fall back to convert methods.
> Closest candidates are:
> MyType(::Int64)
> MyType(::Any)
> call{T}(::Type{T}, ::Any)
> ...
> in map! at abstractarray.jl:1447
> in map! at abstractarray.jl:1444
>
>
>