How to assign the value to be returned by a method? - plc

I have a method which I want to be returning a value. The declaration is clear to me. But how do I assign the value to be returned inside the method implementation?
I can only think of creating an output variable and use that to propagate the value to the caller. But that is definitely not how I would expect a return value to work:
METHOD M_MyMethod : BOOL
VAR_OUT
bReturnVal : BOOL;
END_VAR
// Do some method things here.
// Then assign the return value.
bReturnVal := bWhatever;

The solution is simple:
M_MyMethod := bWhatever;
Using VAR_OUT is also usefull, if you need to return more than one value and don't want to create dedicated type :)

Related

What are the semantics of input variables passed by reference?

Beckhoff's TwinCat-3, as well as Codesys 3 it's based on, adds references as an extension to IEC-61131-3 languages. I'm wondering what is the exact grammar and semantics of this non-standard addition (that's the problem with them: nobody bothers documenting them as well as a standard would).
It the following F_IsNonEmpty function valid and doing what one would expect, when invoked from the F_Test test function below?
FUNCTION F_IsNonEmpty : BOOL
VAR_INPUT
text : REFERENCE TO STRING;
END_VAR
F_IsNonEmpty := LEN(text) > 0;
END_FUNCTION
FUNCTION F_Test1
VAR
testMessage : STRING := '123';
END_VAR
IF F_IsNonEmpty(text := testMessage) THEN
{...}
END_IF
END_FUNCTION
Given that the target of the reference must be initialized using the REF= operator (v.s. e.g. C++ where reference targets are immutable), I'd have expected that the following invoking code would be correct instead - but it doesn't even compile:
FUNCTION F_Test2
VAR
testMessage : STRING := '123';
END_VAR
IF F_IsNonEmpty(text REF= testMessage) THEN
{...}
END_IF
END_FUNCTION
It seems that F_Test1 works correctly, but I'd like someone who actually uses Codesys 3 or TwinCat-3 REFERENCE TO feature to confirm.
When you use a REFERENCE in a VAR_INPUT, it's as if you were using a VAR_IN_OUT variable.
Otherwise if you declare your REFERENCE in the VAR section, you need to use REF= when assigning another variable to it (or get an exception).
In essence, REFERENCE (like a VAR_IN_OUT var) is a more convenient and "safe" pointer because the dereference operator ^ is not needed and because the type is checked at compile time.

How to assign method output to variable by reference MQL4

I'm guessing this question is going to apply to many similar languages other than MQL4 such as c++ (which I also forget how to use) which require you manually specify when you are passing by reference.
Method reference:
int[] previous = GetPrevious(i, ZigZagBuffer);
Method definition:
int GetPrevious[](int current, const double& buffer[])
{
int count = 0;
int result[];
// calculate count
ArrayResize(result,count);
// fill array
return result;
}
The resulting compile error is:
"Invalid Array Access"
From what I understand, this is because array's can only be passed by reference, but you have to explicitly state that you are passing it by reference. But the more I look up the syntax for passing by reference, the more I find articles about passing parameter by reference. (which I already know how to do as you can see in the code example.)
What is the syntax to assign the output of a method to a variable?
In case it matters, I only need to read the array multiple times; I'm not needing to alter or re-assign it after it is declared.
You cannot return array. You have to create it and pass into the function, fill inside the function and that's it.
OnTick(){
double array[]; //declaration of the array
fillArray(array,10); //passing array by ref, updating it there
Print(array[0]=0 && array[9]=9);//returns true
}
void fillArray(double &array[],int size){
ArrayResize(array,size);
for(int i=0;i<size;i++){array[i]=i;}
}

When does Chapel pass by reference and when by constant?

I am looking for examples of Chapel passing by reference. This example works but it seems like bad form since I am "returning" the input. Does this waste memory? Is there an explicit way to operate on a class?
class PowerPuffGirl {
var secretIngredients: [1..0] string;
}
var bubbles = new PowerPuffGirl();
bubbles.secretIngredients.push_back("sugar");
bubbles.secretIngredients.push_back("spice");
bubbles.secretIngredients.push_back("everything nice");
writeln(bubbles.secretIngredients);
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
bubbles = kickAss(bubbles);
writeln(bubbles.secretIngredients);
And it produces the output
sugar spice everything nice
sugar spice everything nice Chemical X
What is the most efficient way to use a function to modify Bubbles?
Whether Chapel passes an argument by reference or not can be controlled by the argument intent. For example, integers normally pass by value but we can pass one by reference:
proc increment(ref x:int) { // 'ref' here is an argument intent
x += 1;
}
var x:int = 5;
increment(x);
writeln(x); // outputs 6
The way that a type passes when you don't specify an argument is known as the default intent. Chapel passes records, domains, and arrays by reference by default; but of these only arrays are modifiable inside the function. ( Records and domains pass by const ref - meaning they are passed by reference but that the function they are passed to cannot modify them. Arrays pass by ref or const ref depending upon what the function does with them - see array default intent ).
Now, to your question specifically, class instances pass by "value" by default, but Chapel considers the "value" of a class instance to be a pointer. That means that instead of allowing a field (say) to be mutated, passing a class instance by ref just means that it could be replaced with a different class instance. There isn't currently a way to say that a class instance's fields should not be modifiable in the function (other than making them to be explicitly immutable data types).
Given all of that, I don't see any inefficiencies with the code sample you provided in the question. In particular, here:
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
the argument accepting b will receive a copy of the pointer to the instance and the return b will return a copy of that pointer. The contents of the instance (in particular the secretIngredients array) will remain stored where it was and won't be copied in the process.
One more thing:
This example works but it seems like bad form since I am "returning" the input.
As I said, this isn't really a problem for class instances or integers. What about an array?
proc identity(A) {
return A;
}
var A:[1..100] int;
writeln(identity(A));
In this example, the return A in identity() actually does cause a copy of the array to be made. That copy wasn't created when passing the array in to identity(), since the array was passed by with a const ref intent. But, since the function returns something "by value" that was a reference, it's necessary to copy it as part of returning. See also arrays return by value by default in the language evolution document.
In any case, if one wants to return an array by reference, it's possible to do so with the ref or const ref return intent, e.g.:
proc refIdentity(ref arg) ref {
return arg;
}
var B:[1..10] int;
writeln(refIdentity(B));
Now there is no copy of the array and everything is just referring to the same B.
Note though that it's currently possible to write programs that return a reference to a variable that no longer exists. The compiler includes some checking in that area but it's not complete. Hopefully improvements in that area are coming soon.

What makes a property a computed property in Swift

Let's started with the code snippet:
St Foo {
var proA: Int = 0 { // needs initialization
willSet {
print("about to set proA to \(newValue) from \(proA)")
}
didSet {
print("already set proA to \(proA) from \(oldValue)")
}
}
var ProB: Int { // do not needs initialization
return 1
}
}
let foo = Foo()
foo.proA = 23
print(foo.ProB)
Here are some of my personal understandings about the the stored and computed property:
a: Property with only the observer (willSet and didSet) is not a computed property but a stored property (ex. the proA property in the code above).
b: Computed property must not has initialization (See the comments of the code above).
c: setter is kind of equal to the property observer, the property observer is just the setter + the observer to of the before and after mutating.
Questions:
1. I wonder what makes a property a computed property? Is it correct that as long as the property has a getter and return it is a computed property?
2. Are all my understandings (a, b & c) correct? If not, would be nice of you to point out.
3. Why is it not allowed to initialize an computed property? (Please see the figure below) And when I do so the compiler gives out the warning Cannot call value of none-function type "int" What's the meaning of this error?
Thanks a lot.
First, this is about variables, not properties. Any variable can be a computed variable. A property is just one way to use a variable.
I think on the whole you are making a big mistake in putting a stored variable with setter observers side by side with a computed variable. They are unrelated!
Think of a computed variable as something that looks and acts like a variable when you use it — you get and (maybe) set it — but is in fact a function (or a pair of functions). It is just a compact way of calling a function. That's all it is.
A stored variable with observers, on the other hand, is just a stored variable that also has some observers.
Okay, on to your questions:
I wonder what makes a property a computed property? Is is correct that as long as the property has a getter and return it is a computed property?
Yes. It's a computed variable because you declared it using the syntax that makes it a computed variable (with the curly braces).
Are all my understandings (a, b & c) correct? If not would be nice of you to point out
Yes. I think your "c" is quite insightful: a computed variable does not need a setter observer because it has (gasp!) a setter!
Why is it not allowed to initialize an computed property? (Please see the figure below) And when I do so the compiler gives out the warning Cannot call value of none-function type "int" What's the meaning of this error?
There is no sense in which a computed variable "has" a value — it is computed! it's just some functions! — so it makes no sense to assign it an "initial" value.
A stored property is a property of which the property value is stored together with the instance of the class or struct. The value may be changed, but the property can also be a constant. Thus a stored property can be as simple as:
var proA: Int
let proB: Int
var proC: Int = 0
Computed properties do not store a value. Thus you cannot assign a value to a computed property. A Computed property should have a getter that returns a value. I a broad term, you can think of a computed property as a property that returns the value of a function.
Example of Computed Property
var proA: Int {
return proB * proC
}
With regards to your questions:
Computed Property is therefor a property that do not store a value, and contains a get to return the 'computed' value of the property.
a is correct, b computed properties should not have initialization, c if you mean willSet and didSet. Yes they are like observers for when the property's value will change and did change respectively
Since the value of a computed property is not stored and will never be used, the compiler forbids it.
Hope this helps a bit.
I wonder what makes a property a computed property? Is is correct that as long as the property has a getter and return it is a computed property?
If you define get { } inside the property declaration, it makes that property to a computed property.
And it cannot have initial value as when you access the property, it will always call get{} function declared in property.
Are all my understandings (a, b & c) correct? If not would be nice of you to point out
a is correct
b is wrong.
You can not set initial value for computed property.
Because as I explained in question 1, it will always return result of get{} when you need access to the property.
c : 50% right
setter , it can also be used as to store newValue into another private variable and you can do some additional observing logic. So to observe value changes on stored property, you use willSet and didSet
You can define observing logic on computed property (which has getter and setter) on set{} declaration. But main purpose of set {} is to store the value to another variable or for example UserDefaults.
Why is it not allowed to initialize an computed property? (Please see the figure below) And when I do so the compiler gives out the warning Cannot call value of none-function type "int" What's the meaning of this error?
Same answer
Your code makes compiler to be confused
When you set initial value on the property on declaration, the compiler tries to understand it as stored property. But you also defined get{} for this property, and it means it is computed property and should always return 22 when you access the property. So you should remove one of two.
a. Yes,a property with only observer is a stored property not a computed property.Beacuase property observer tracks the value of a property whose value has initialised previously & it's now changing ,that's a stored property. It's not applicable for a computed property since it has no predefined value
b. computed property is a property whose value depends on other variables, we should declare only those properties as computed property , who needs to be computed using value of another variables ,so it's value cannot be initialised in advance.
for e.g. - If we have 2 variables a & b. we need their addition value , so a variable named 'sum' is used , then sum will be declared as a computed property & its get{} block will return (a+b) that's sum of a & b & the value of sum variable.Then in this case we can't initialise property 'sum'
in advance because it will be computed using a & b.
c. Setter is not an observer it sets value of another variable or performs some actions related to other variables whereas a property observer tracks changes in value of its associated variable itself. for e.g. it's meaningless to use a property observer for variable 'sum' as described in point b .

Correct way to return function value instead of binding in Coffeescript

I can't seem to find a concise answer to this question. What is the correct coffeescriptic way to return the value from _otherInstanceMethod when calling #_instanceMethod instead of the function binding itself?
x = _instanceMethod: () ->
#_otherInstanceMethod key: 'value'
Edit (thanks commenters)
This returns:
x = function () {
[...] # function body omitted
});
Instead of
x = 'some value returned by _otherInstanceMethod'
I would like the value to be returned instead of the function binding to _otherInstanceMethod
Being totally new to Coffeescript, this was my fault. I was calling the instance method like:
#_instanceMethod
instead of
#_instanceMethod()
Sorry for the trouble, voting to delete
In CoffeeScript #something translated into this.something regardless of the underlying variable type. This means you can use # only in conjuction with properties, with methods you still ought to use good old this.