Stan: Local scopes in functions - scope

I am fairly new to Stan and have gone through the manual (version 2.23). What was new to me was that variable hiding is not allowed: you can not use a local variable (e.g. in a for-loop) that has been defined globally (i.e. outside the for-loop) (chapter 7.9, Local Variable Declarations).
Is the same true for user-defined functions? I.e., can you declare variables in user-defined functions that have the same name as other variables, that have been declared outside the function? In our case, we have
functions{
real[] my_function (x) {
real init[K*2] = some_declaration_involving_x
return(some_other_value_involving_init[])
}
}
transformed data {
real init[K*6] = some_other_declaration; // initial values
}
transformed parameters {
yet_another_variable = my_function(some_variable)
}

Yes, it's easy enough to test:
functions {
int fun() {
int N = 1;
return N;
}
}
model {
real N = 2;
print(fun(), N);
}

Related

Javascript. What is the functional equivalent for class constructors?

Class constructor initializes and create objects/functions in a class. If I'm using functions, how would I initialize a function within the function?
This is the simple class
export default class MainProcess{
constructor() {
this.isReady = false
this.init()
}
init() {
this.setupApplicationMenu()
this.initWindowManager()
this.getIcons()
}
}
how can I initiate a MainPRocess Function?
While I'm not entirely sure I understand the question, I think you're asking "How can I create a function in a way that's similar to how I'm used to writing classes, but without using the class keyword?" Here's an example of that:
function Example () {
this.value = 10;
// instance method
this.print = function () {
console.log(this.value);
}
}
// static method
Example.printHello = function () {
console.log('hello world');
}
const example1 = new Example();
example1.print(); // 10
example1.value = 20;
example1.print(); //20
console.log(Object.getPrototypeOf(example1).constructor.name); // "Example"
const example2 = new Example();
example2. print(); //10
Example.printHello(); // "hello world"
Functions are part of the class. Classes are a grouping of functions(methods) and data(as properties). These functions are used to modify properties.
In the above example, you created a class MainProcess with some functions. However, functions defined in the init method is not present. The compiler will throw an error.
constructor is a special method used to create an object with that class.
If I'm using functions, how would I initialize a function within the
function?
It seems you are mixing two concepts function constructors in JS and Classes which are introduced later. Class is nothing, but a syntactic sugar on function constructor. JS is a prototype-based language.
difference b/w function and function constructor?
Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created. This is different from using Global_Objects/eval with code for a function expression.
var x = 10;
function createFunction1() {
var x = 20;
return new Function('return x;'); // this |x| refers global |x|
}
function createFunction2() {
var x = 20;
function f() {
return x; // this |x| refers local |x| above
}
return f;
}
var f1 = createFunction1();
console.log(f1()); // 10
var f2 = createFunction2();
console.log(f2()); // 20
I highly recommend you first understand the how JS has implemented class in it.

How to access attributes in object dynamically in Raku

I wonder howto access an object's attribute dynamically via a name as a Str at runtime in Raku. Instead of:
#!/usr/bin/rakudo
class c0 {
has $!a0 = 1;
has $!a1 = 2;
method access(Str $m) {
if ($m eq "a0") { return $!a0; }
if ($m eq "a1") { return $!a1; }
}
method set(Str $m, $v) {
if ($m eq "a0") { $!a0 = $v; }
if ($m eq "a1") { $!a1 = $v; }
}
}
my $c = c0.new();
$c.set("a0", 3);
$c.set("a1", 4);
say $c.access("a0");
say $c.access("a1");
I would like to use something that would look in pseudocode:
class c0 {
...
method access(Str $m) {
return self.$m;
}
method set(Str $m, $v) {
self.$m = $v;
}
}
Is this possible in Raku? Which construct do I need to use?
As a backgrounder I was thinking how to implement a role that adds associativity functionality to the class, to transparently access a member. The attribute name would be parametrized: If I have a class class ports { has #!ports_; ... } and an instance my $p = ports.new() then I want to be able to use the subscript syntax to access #ports_ via $p[...] . I try to figure out weather I can define role acc [ Str $member] does Associative[Cool,Str] { ... } and then define ports via class ports does acc["ports_"] { ... }
where the AT-KEY and EXISTS-KEY in role acc are implemented using dynamic attribute access (if that is possible).
I dont want to use "EVAL".
This is possible with some introspection of the attributes. However, I would like to point out that it is the exact intention of private attributes to be private. Creating a workaround to handle them as public attributes is an anti-pattern, and introduces needless complexity.
class c0 {
has $.a0 = 1;
has $.a1 = 2;
method access (Str $m) {
my $attribute = self.^attributes.first({ ~$_ eq '$!' ~ $m });
return unless $attribute;
$attribute.get_value(self); # 1
}
}
my $c = c0.new;
say $c.access('a0');
For setting the value, you can use the .set_value method on the attribute.
method set (Str $m, $v) {
...
$attribute.set_value(self, $v);
}
Old answer left here for historic purposes.
Yes, something like this is possible in Raku. You don't even need to explicitly define the access method.
class c0 {
has $.a0 = 1;
has $a.1 = 2;
}
my $c = $c0.new;
say $c.'a0'(); # 1
This works because Raku creates an accessor method for public variables for your classes, which is called when you use .'a0'(). The () are required for using a quoted method name.
You changed your post to add a question about how to do something like this:
role acc [ Str $member] does Associative[Cool,Str] { ... }
class ports does acc["ports_"] { has #!ports_; ... }
The answer is of course, don't do that.
I mean you can, but you really shouldn't.
I mean you really really shouldn't.
Also you indicate that you want to use [] for indexing.
The thing is that is Positional not Associative.
(I'm ignoring the fact that there is no point to add _ to the end of the attribute name. Usually in Perl or Python adding _ indicated private, but we don't need to do that in Raku.)
The right way to do that is to have the array inside of the role.
role Array::Access [::OF = Cool] does Positional[OF] {
has OF #!array-access handles < AT-POS >;
}
class Ports does Array::Access {
# allows you to access it as self!ports inside of this class
method !ports () is raw { #!array-access }
}
Which shows that adding a role to do that is probably overkill.
class Ports does Positional[Cool] {
has Cool #!ports handles < AT-POS >;
}
If you really, really want to do it they way you asked for, the following works.
role Inner::Array::Access [ Str:D \name, ::OF = Cool ] does Positional[OF] {
# a way to quickly access the attribute
# (hopefully no-one tries to add an attribute of this name to their class)
has $!inner-array handles < AT-POS >;
# set $!inner-array
submethod TWEAK (){
$!inner-array := self.^attributes.first(name).get_value(self);
}
}
class Ports does Inner::Array::Access['#!ports'] {
has #!ports;
# a quick way to add a way to set #!ports for our test
submethod BUILD( :#!ports ){}
}
my Ports $v = ports => [0,10,20,30];
say $v[2]; # 20
Probably what you were thinking is embed the self.^attributes thing into AT‍-‍POS.
role Inner::Array::Access [ Str:D \name, ::OF = Cool ] does Positional[OF] {
method AT-POS ( \index ) is raw {
self.^attributes.first(name).get_value(self).AT-POS(index);
}
}
That would be slow, because it has to do all of those lookups everytime you access a single element.

Simple loop inside template -- variable 'x' cannot be read at compile time

(Note that I am extremely new to DLang (first day) so I am probably doing something very stupid)
I am trying to create a mixin template to re-use in my app's domain classes, which will automatically generate a toString1() method at compile-time, which will loop through the implementing struct's properties and generate code to print them.
To accomplish this, I am getting a const array of all of the struct's properties and trying to loop through them. However, when I try to access the index inside the loop (which should be perfectly executable at compile-time -- since we are looping against a known value) it fails.
It works completely fine if I use hard-coded indexes.
template Printable() {
import std.algorithm.iteration;
import std.conv;
import std.meta;
import std.stdio;
import std.format;
import std.range;
import std.typecons;
string toString1() const {
const auto traits = __traits(allMembers, typeof(this));
const auto internalWrap = (const string s) => "`" ~ s ~ ": ` ~ this." ~ s ~ " ~ `\n`";
const auto ret = iota(0, traits.length)
.map!((const int x) => traits[x]) // Error: variable x cannot be read at compile time
.fold((a, b) => a ~ b);
pragma(msg, internalWrap(traits[0])); // WORKS GREAT
return "";
}
}
(Just a note that I also tried doing it using both for-loops as well, but it fails with the same error).
I wanted to put an answer on this so this is a code example about what we went over in the comments:
struct A {
int a;
string b;
mixin Printable; // adds the toString1 method
}
mixin template Printable() {
string toString1() const {
string s;
import std.conv;
// loop over the trait directly, don't try to feed it
// through variables to ensure still available
foreach(memberName; __traits(allMembers, typeof(this))) {
// this ensures we are only actually trying to print actual fields
// (only fields have an offsetof property) since printing member
// variables will not be helpful
static if(is(typeof(__traits(getMember, this, memberName).offsetof))) {
if(s.length)
s ~= "\n";
// name
s ~= memberName;
s ~= " = ";
// value, converted to string
s ~= to!string(__traits(getMember, this, memberName));
}
}
return s;
}
}
void main() {
import std.stdio;
A a = A(14, "string");
writeln(a.toString1());
}
prints
a = 14
b = string

Why is the struct unknown at compiletime in the code?

I was wondering how I could change the code below such the bmBc is computed at compile time . The one below works for runtime but it is not ideal since I need to know the bmBc table at compile-time . I could appreciate advice on how I could improve on this.
import std.conv:to;
import std.stdio;
int [string] bmBc;
immutable string pattern = "GCAGAGAG";
const int size = to!int(pattern.length);
struct king {
void calculatebmBc(int i)()
{
static if ( i < size -1 )
bmBc[to!string(pattern[i])]=to!int(size-i-1);
// bmBc[pattern[i]] ~= i-1;
calculatebmBc!(i+1)();
}
void calculatebmBc(int i: size-1)() {
}
}
void main(){
king myKing;
const int start = 0;
myKing.calculatebmBc!(start)();
//1. enum bmBcTable = bmBc;
}
The variables bmBc and bmh can't be read at compile time because you define them as regular runtime variables.
You need to define them as enums, or possibly immutable, to read them at compile time, but that also means that you cannot modify them after initialization. You need to refactor your code to return values instead of using out parameters.
Alternatively, you can initialize them at runtime inside of a module constructor.

Spock unit testing and Inner closures

I ran into a rather odd closure issue related to spock unit testing and wondered if anyone could explain this.
If we imagine a dao, model, and service as follows:
interface CustomDao {
List<Integer> getIds();
Model getModelById(int id);
}
class CustomModel {
int id;
}
class CustomService {
CustomDao customDao
public List<Object> createOutputSet() {
List<Model> models = new ArrayList<Model>();
List<Integer> ids = customDao.getIds();
for (Integer id in ids) {
models.add(customDao.getModelById(id));
}
return models;
}
}
I would like to unit test the CustomService.createOutputSet. I have created the following specification:
class TestSpec extends Specification {
def 'crazy closures'() {
def mockDao = Mock(CustomDao)
def idSet = [9,10]
given: 'An initialized object'
def customService = new CustomService
customService.customDao = mockDao
when: 'createOutput is called'
def outputSet = customService.createOutputSet()
then: 'the following methods should be called'
1*mockDao.getIds() >> {
return idSet
}
for (int i=0; i<idSet.size(); i++) {
int id = idSet.get(i)
1*mockDao.getModelById(idSet.get(i)) >> {
def tmp = new Model()
int tmpId = id // idSet.get(i)
return tmp
}
}
and: 'each compute package is accurate'
2 == outputSet.size()
9 == outputSet.get(0).getId()
10 == outputSet.get(1).getId()
}
}
Notice that in here I test two things. First, I initialize the dao with my mock, verify that the daos are correctly called and return the proper data, and then I verify that I get the proper output (i.e. "and:").
The tricky part is the for loop, in which I wanted to return models from the mock dao that are related to the method parameter. In the above example, if I use a simple for (__ in idSet), the models only return with id 10: outputSet.get(0).getId() == outputSet.get(1).getId() == 10. If I use the traditional for loop, and set the model with idSet.get(i), I get an IndexOutOfBoundsException . The only way to make this work is by retrieving the value in a local variable (id) and setting with variable, as above.
I know this is related to groovy closures and I suspect that spock captures the mock calls into a set of closures before executing them, which means that the model creation depends on the outer state of the closure. I understand why I would get the IndexOutOfBoundsException, but I don't understand why int id = idSet.get(i) is captured by the closure whereas i is not.
What is the difference?
Note: this is not the live code but rather simplified to demonstrate the crux of my challenge. I would not and do not make two subsequent dao calls on getIds() and getModelById().
While stubbing getModelById by a closure, the arguments to the closure has to match with that of the method. If you try something like below, you would not need the local variable id inside for anymore.
for (int i=0; i<idSet.size(); i++) {
//int id = idSet.get(i)
mockDao.getModelById(idSet.get(i)) >> {int id ->
def tmp = new Model()
tmp.id = id // id is closure param which represents idSet.get(i)
return tmp
}
}
Simplified version would be to use each
idSet.each {
mockDao.getModelById(it) >> {int id ->
def tmp = new Model()
tmp.id = id // id is closure param which represents idSet.get(i)
tmp
}
}
Do we need to worry about how many times method is called if it is being stubbed?
Accessing mutable local variables from a closure whose execution is deferred is a common source of errors not specific to Spock.
I don't understand why int id = idSet.get(i) is captured by the closure whereas i is not.
The former gives rise to a separate hoisted variable per iteration whose value is constant. The latter gives rise to a single hoisted variable whose value changes over time (and before the result generator executes).
Instead of solving the problem by introducing a temporary variable, a better solution (already given by #dmahapatro) is to declare an int id -> closure parameter. If it's deemed good enough to stub the calls without enforcing them, the loop can be omitted altogether. Yet another potential solution is to construct the return values eagerly:
idSet.each { id ->
def model = new Model()
model.id = id
1 * mockDao.getModelById(id) >> model
}

Resources