Any reason not to just use a for loop for this? "map_without_result(add_one!, A)" is three characters longer than "for x in A; add_one!(x); end" and the semicolons are unnecessary.
On Tue, Jun 9, 2015 at 5:06 PM, Tom Breloff <[email protected]> wrote: > Ideally I don't have to assume anything about the return value (all I care > about is the side effect). > > > On Tuesday, June 9, 2015 at 4:58:36 PM UTC-4, Scott T wrote: >> >> 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 >>> >>> >>>
