views:

78

answers:

1

Mathematica has a function MapThread that behaves like this:

MapThread[ f , { {a,b,c} , {d,e,f} } ]
-> { f[a,d] , f[b,e] , f[c,f] }

I'd like to implement this in TeX, which has very primitive programming facilities. I've basic facilities for iterating over lists, but no logical indexing into them. Given this restriction, is there an algorithm for looping synchronously though multiple lists?

I could write something like the following: (pseudocode)

ii = 0; jj = 0;
for elem1 in list1
  ii = ii+1
  for elem2 in list2
    jj = jj+1
    if ii == jj
      return ( elem1 , elem2 )
    fi
  end
end

but it seems terribly inefficient. Note that the big restriction is that I can't access elements of lists numerically, so something like the following is too "high level":

for ii = 1:length(list1)
  func ( list1(ii) , list2(ii) )
end

The reason this restriction is in place is that in order to implement list1(ii) I'd need to write something like the following in the first place:

jj = 0
for elem1 in list1
  jj = jj+1
  if ii=jj
    return elem1
  fi
end

Or is the inefficient case probably the best I'll be able to do with such a primitive language?

+2  A: 

In pseudocode, as long as you can test whether a list is empty, you can do it like so:

while (list1 is not empty) and (list2 is not empty)
  x1 = first(list1);
  x2 = first(list2);
  list1 = rest(list1);
  list2 = rest(list2);

  func(x1, x2);
end while

It's still not going to win any beauty contests, but it'll get the job done without being crushingly inefficient.

Pillsy