How to use function to automatically calculate in table?

I want a command to automatically add the first and second columns, and put the result into the third column.

Someting wrong as below:

#let mytable(data) = table(
  columns: 3,
  stroke: 1pt black,
  [X value], [Y value], [X+Y],
  ..data.map((x, y) => [x, y, x + y])
)

#mytable((
  (1, 2),
  (3, 4),
  (5, 6)
))

Maybe I misunderstand the map or something else… How can I do? Thanks!

Fixing the function calling syntax like this is the first step:

#let mytable(data) = table(
  columns: 3,
  stroke: 1pt + black,
  [X value], [Y value], [X+Y],
  ..data.map(((x, y)) => [x, y, x + y])
)

That makes

image

Need to use #x to use a variable inside content, and also need to give one content value per table cell. The complete fix:

#let mytable(data) = table(
  columns: 3,
  stroke: 1pt + black,
  [X value], [Y value], [X+Y],
  ..data.map(((x, y)) => ([#x], [#y], [#(x + y)])).flatten()
)

#mytable((
  (1, 2),
  (3, 4),
  (5, 6),
))

Every call to the map(f) function f creates one table row, but in the end the table wants all cells in a single array, so we .flatten() the result.

image

2 Likes

Thanks! But I am still a little currious about why there need two ((x,y)) here? the inner stand for the input (1,2), and the outer one stand for the parameter of this anonymous function?

Each element in the data array is itself an array (1, 2) and so on. I guess it’s like this

data.map( ( (x, y) ) => none)
             \_ Unpack first argument into two values.
           \_ The function arguments (of anonymous function)

Without the extra layer of () it would be ambiguous if the unnamed function takes 2 parameters or if it takes 1 and unpacks it.

2 Likes