Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Variable going out of scope when other variables are defined #922

Open
sanitgupta opened this issue Feb 22, 2019 · 2 comments
Open

Variable going out of scope when other variables are defined #922

sanitgupta opened this issue Feb 22, 2019 · 2 comments
Labels

Comments

@sanitgupta
Copy link

var P = function() {
  return flip(theta) ?  'a' : 'b';
}

var fn = function() {
  return sample(Beta({a: 1, b: 1}))
}

//var x = sample(Beta({a: 1, b: 1}));
var theta = 0.1;
theta;

var dist = Infer(
  {method: 'MCMC', kernel: 'MH', samples: 1000},
  P);

viz.auto(dist)

This code runs fine but when I uncomment the line initializing x, the code gives an error 'theta is not defined' . I am not sure how/why this is happening. Apologies if it isn't a bug.

@null-a
Copy link
Member

null-a commented Feb 22, 2019

Thanks for taking the time to open this issue!

The way to make this work regardless of whether var x = ... is commented out or not, is to move var theta = ... to the top of the program. (Before theta is mentioned in P.)

I'm not sure whether we expect it to be possible to write var theta = ... after defining P and have things work, but that fact that this sometimes works and sometimes doesn't seems like a bug either way.

I am not sure how/why this is happening.

As part of compilation, the program is transformed into continuation passing style. When var x = sample(...) is present, everything after it appears inside a new function, and because that new function introduces a new scope theta isn't visible from P.

In other words, without the call to sample, the program generates JS something like this:

var P = function() {
  return theta;
};
var theta = 100;
P();

... but with the call to sample we get something like:

var P = function() {
  return theta;
};
(function() {
  var theta = 100;
  P();
})();

@null-a null-a added the bug label Feb 22, 2019
@sanitgupta
Copy link
Author

Thanks so much for the explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants