I wrote myself a foreach, which I'm using from time to time.
foreach(println, array)
It's not a big win, but in some cases it feels nicer than a for.

Am Dienstag, 9. Juni 2015 21:39:11 UTC+2 schrieb Tom Breloff:
>
> 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
>
>
>

Reply via email to