Data shapes and call forms

This chapter exists specifically for the most common WebPPL pain point: “I passed a list in the wrong shape and the docs didn’t tell me.”

Arrays (a.k.a. “lists”)

In WebPPL, the usual “list” is a JavaScript-style array literal: [a, b, c].

Example: map(fn, arr)

1var xs = [0, 1, 2];
2var ys = map(function(x) { return x + 1; }, xs);
3display(ys);
[ 1, 2, 3 ]
undefined

Options objects (named arguments)

Some functions use an options object as their first argument. That is a JavaScript object literal: {key: value, ...}.

Example: mapData({data: arr[, batchSize: n]}, fn)

1var xs = [10, 20, 30];
2
3// mapData: first arg is an OPTIONS OBJECT with key `data`.
4// The function receives (element, index).
5var ys = mapData({data: xs}, function(x, i) { return [i, x / 10]; });
6
7display(ys);
[ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ] ]
undefined

Tensors: dims + flat array

Tensor constructors often take:

  • dims: an array of dimension sizes (e.g. [2, 2, 2])

  • arr: a flat array of values

Example: Tensor(dims, arr)

1// Tensor(dims, arr): dims is an array of dimensions, arr is a FLAT array.
2var t = Tensor([2, 2], [1, 2, 3, 4]);
3display(t);
Tensor {
  dims: [ 2, 2 ],
  length: 4,
  data: Float64Array(4) [ 1, 2, 3, 4 ]
}
undefined

Inference call form (always options object)

Inference is typically invoked via an options object:

Infer({method: 'enumerate', model: model})

1var model = function() {
2  return flip() + flip();
3};
4
5// Enumeration is deterministic for finite models.
6var dist = Infer({method: 'enumerate', model: model});
7display(dist);
dist {
  params: { dist: { '0': [Object], '1': [Object], '2': [Object] } },
  supp: [ 0, 1, 2 ],
  getDist: [Function (anonymous)]
}
undefined