Skip to content

Commit

Permalink
Add map for 2 input args.
Browse files Browse the repository at this point in the history
  • Loading branch information
ViralBShah committed Aug 20, 2011
1 parent 7a8960f commit f2dba4a
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions j/abstractarray.j
Original file line number Diff line number Diff line change
Expand Up @@ -842,39 +842,48 @@ isempty(a::AbstractArray) = (numel(a) == 0)
#map(f, v::AbstractVector) = [ f(v[i]) | i=1:length(v) ]
#map(f, M::AbstractMatrix) = [ f(M[i,j]) | i=1:size(M,1), j=1:size(M,2) ]

## TODO: How to generalize map to n input args?
function map_to(dest::AbstractArray, f, A::AbstractArray)
for i=1:numel(A)
dest[i] = f(A[i])
end
return dest
end

function map(f, A::AbstractArray)
if isempty(A)
return A
function map_to(dest::AbstractArray, f, A::AbstractArray, B::AbstractArray)
for i=1:numel(A)
dest[i] = f(A[i], B[i])
end
return dest
end

function map(f, A::AbstractArray)
if isempty(A); return A; end
first = f(A[1])
dest = similar(A, typeof(first))
map_to(dest, f, A)
# dest[1] = first
# for i=2:numel(A)
# dest[i] = f(A[i])
# end
# return dest
end

#obsolete code, mainly here for reference purposes, use gen_cartesian_map
function cartesian_map(body, t::Tuple, it...)
idx = length(t)-length(it)
if idx == 0
body(it)
else
for i = t[idx]
cartesian_map(body, t, i, it...)
end
end
return map_to(dest, f, A)
end

function map(f, A::AbstractArray, B::AbstractArray)
if size(A) != size(B); error("Input size and shape should be same"); end
if isempty(A); return A; end
first = f(A[1], B[1])
dest = similar(A, typeof(first))
return map_to(dest, f, A, B)
end

## Obsolete - Mainly here for reference purposes, use gen_cartesian_map
# function cartesian_map(body, t::Tuple, it...)
# idx = length(t)-length(it)
# if idx == 0
# body(it)
# else
# for i = t[idx]
# cartesian_map(body, t, i, it...)
# end
# end
# end

## Transpose, Permute ##

reverse(v::AbstractVector) = [ v[length(v)-i+1] | i=1:length(v) ]
Expand Down

0 comments on commit f2dba4a

Please sign in to comment.