How structs are extended just importing packages in D? - import

I have this fibonacci number generator.
struct FibonacciSeries
{
int first = 0;
int second = 1;
enum empty = false;
#property int front() const
{
return first;
}
void popFront()
{
int third = first + second;
first = second;
second = third;
}
#property FibonacciSeries save() const
{
return this;
}
}
This struct does not have the take method, so I have this error when executing this command (writeln(FibonacciSeries().take(5))).
a.d(66): Error: no property 'take' for type 'FibonacciSeries'
However, by importing range package, it has the take method. What's the mechanism behind this?

The mechanism is Uniform Function Call Syntax:
http://dlang.org/function.html#pseudo-member
To put it simply, if a.foo(b...) is not valid, the compiler tries rewriting it to foo(a, b...).

Related

How to pass function to dart constructor?

I want to define a constructor that takes fanction as parameter and return a value
Like this:
class app {
app({itemBuilder: itemBuilder});
int itemBuilder(int? index) {
return 1;
}
}
The question is unclear, but here is a snippet of passing the function as a parameter
class app {
final Function app;
app({this.itemBuilder: itemBuilder});
}
final obj = app(itemBuilder: (){
})
I think what you need is the static function to create and return a value.
class AppData890 {
static int itemBuilder(int index) {
return 1;
}
}
use it like this
AppData890.itemBuilder(1);
If you need it as you state the question
Tornike is ri8.
for more info about static head to
https://dart.dev/guides/language/language-tour#class-variables-and-methods
Flutter doesn't allow what you did because The default value of an optional parameter must be constant. Just try with this
class app {
app({itemBuilder});
int itemBuilder(int? index) {
return 1;
}
}
or you can also try and no need to use constructor.
class app {
static int itemBuilder(int? index) {
return index??1;
}
}
// call from outside
app.itemBuilder(5);

Drool Rules: Arithmetic Operations

I'm trying to write a simple rule. To perform a set of calculations. I understand that the calculations can be handled via functions. But, The business logic involves calculations.
package com.sample.rules
import com.sample.rules.Test
rule "Calculate"
when
Test(calculate == true)
then
finalValue = Test(InitialValue) + 10;
Test.setFinalValue(finalValue)
System.out.println("FinalValue=" + Test.getFinalValue();
end
The Class file with variable
public class Test {
private int finalValue;
private int initialValue;
private boolean calculate;
public int getFinalValue() {
return FinalValue;
}
public void setFinalValue(int FinalValue) {
this.FinalValue = FinalValue;
}
public int getInitialValue() {
return InitialValue;
}
public void setInitialValue(int InitialValue) {
this.InitialValue = InitialValue;
}
public boolean isCalculate() {
return calculate;
}
public void setCalculate(boolean calculate) {
this.calculate = calculate;
}
}
The App file is as shown below
public class CalculationApp {
public static void main(String[] args) {
System.out.println( "Bootstrapping the Rule Engine ..." );
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
Test test = new Test();
test.setInitialValue(20);
test.setCalculate(true);
kSession.insert(test);
int fired = kSession.fireAllRules();
System.out.println( "Number of Rules executed = " + fired );
}
}
The rule file throws an error :
Rule Compilation error finalValue cannot be resolved to a variable
Cannot make a static reference to the non-static method getInitialValue() from the type Test
finalValue cannot be resolved to a variable
Cannot make a static reference to the non-static method getFinalValue() from the type Test
While I found the answer by Trial and Error: I'm trying to understand the logic behind it. I mean, Assigning a variable (I understand variable has a different meaning) /assignment in the when condition is understandable, but the same the how does the Then part work. I mean, the item.setFinalValue(...) part.
Your rule has several problems, as indicated by the error.
Rule Compilation error finalValue cannot be resolved to a variable
finalValue cannot be resolved to a variable
The first problem is that you never declare finalValue, just attempt to assign to it on the right hand side. To fix this, simply declare finalValue. Assuming it's an integer:
int finalValue = ...
This is identical to how it works in Java.
However given what the original rule looks like, I think you're trying to pull the initial value from the Test object. To do that, you would do something like this:
rule "Calculate"
when
Test( calculate == true,
$initialValue: initialValue ) // assign the $initialValue variable
then
int finalValue = $initialValue + 10; // set finalValue by adding 10 to $initialValue
Cannot make a static reference to the non-static method getInitialValue() from the type Test
Cannot make a static reference to the non-static method getFinalValue() from the type Test
Both of these errors indicate that you're trying to call instance methods without an object instance. This is once again the same as in Java, where if you have an instance method you must call it against an instance.
Assuming these are methods on the Test class, you would change your rule to be:
package com.sample.rules
import com.sample.rules.Test
rule "Calculate"
when
$test : Test( calculate == true,
$initialValue: initialValue )
then
int finalValue = $initialValue + 10;
$test.setFinalValue(finalValue); // call against $test instance
System.out.println("FinalValue=" + $test.getFinalValue()); // you were also missing a parenthesis
end
What worked was :
rule "Calculate"
when
item: Test(calculate == true)
then
item.setFinalValue(item.getInitialValue() + 10)
System.out.println("FinalValue=" + item.getFinalValue();
end

How to call the method of unknown class in MQL?

I've a Collection class which aims to store different kind of objects, however I'd like to call specific method name which these classes share (e.g. ToString()).
Here is my attempt:
class Collection {
public:
void *data[];
void Collection() {}
void ~Collection() {
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) delete data[i];
}
}
void *Add(void *_object) {
uint _size = ArraySize(data);
ArrayResize(data, _size + 1, 100);
data[_size] = _object;
return _object;
}
string ToString(string _dlm = ",") {
string _out = "";
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) {
_out += ((void *) data[i]).ToString(); // #fixme: Syntax error.
}
}
return _out;
}
};
However using ((void *) data[i]).ToString() syntax fails with:
'ToString' - member function not defined Collection.mqh
How can I call a ToString() method for each stored object?
It seems to me that it should be something like collection.toString() where collection is an object of your class Collection. Then each object that you add to your collection should implement this function... Maybe it is easier to mention some superclass that supports toString() (or interface with this method) and make sure that you add only correct objects? This also makes your code free of unexpected errors in runtime.
Also CArrayObj is at your disposal with most functions, if you need toString() or any other function then you can simply extend basic class. Maybe the only disadvantage of the default collection is that it stores CObject-inherited objects.
This can be achieved by creating an abstract class where all classes can share the same virtual method. For example:
class Object {
public:
virtual string ToString() = NULL;
};
class Foo : public Object {
public:
virtual string ToString() {
return "Foo";
};
};
class Bar : public Object {
public:
virtual string ToString() {
return "Bar";
};
};
Then in the Collection class the following method:
virtual string ToString(string _dlm = ",") {
string _out = "";
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) {
_out += ((Object *) data[i]).ToString() + _dlm;
}
}
return _out;
}
Sample usage:
Collection *objects;
objects = new Collection;
Foo *foo = new Foo();
Bar *bar = new Bar();
objects.Add(foo);
objects.Add(bar);
Print(objects.ToString());
delete objects;

class member functions with pointer parameters

I have this homework assignment that is giving me a lot of trouble right now. My teacher is very vague in class and hard to communicate with. I will try very hard to articulate my thoughts here.
Here is the assignment:
(3pts) Given the following class header file, write the class’ source
code for each of the accessor and mutator functions listed. (Pay
attention to how the functions have listed their parameters, varying
between passing by reference and by value.) Don’t forget to comment
your code – it counts!
class Album {
private:
char * artist; // band or singer’s name
char * title; // title of the album
int year_released; // year the album is released
char * record_label; // name of company produced album
int num_songs; // number of songs on the album
int num_minutes_long; // length (mins) of album
char * genre; // genre of artist (eg, rock, pop, …)
public:
//constructors
Album();
Album(char *& a, char *& t);
//deconstructor
~Album();
//accessors and mutators
bool set_artist(char * a);
bool set_title(char * t);
bool set_year_released(int value);
bool set_record_label(char *& label);
bool set_num_songs(int value);
bool set_num_minutes_long(int value);
bool set_genre(char * g);
bool get_artist(char *& a);
bool get_title(char *& t);
int get_year_released();
bool get_record_label(char *& label);
int get_num_songs();
int get_num_minutes_long();
bool get_genre(char *& g);
};
Here is my work so far:
bool Album::set_artist(char * a)
{
*artist = a;
}
bool Album::set_title(char * t)
{
*title = t;
}
bool Album::set_year_released(int value)
{
year_released = value;
}
bool Album::set_record_label (char *& label)
{
*record_label = label;
}
bool Album::set_num_songs(int value)
{
num_songs = value;
}
bool Album::set_number_minutes_long(int value)
{
num_minutes_long = value;
}
bool Album::set_genre(char * g)
{
*genre = g;
}
bool Album::get_artist(char *& a)
{
return artist;
}
bool Album::get_title(char *& t)
{
return title;
}
int Album::get_year_released()
{
return year_released;
}
bool Album::get_record_label(char *& label)
{
return *record_label;
}
The input will be an array.
My questions:
First, am I on the right track?
When using (char * a) for a function, for example, this is passing the address of a, correct? so then *artist=a; changes what the address of a points to?
Also, the functions are bool when I would expect void. Why?
For all of the set_xxx functions, the parameter is *... but for set_record_label it is *&. That appears to be a mistake to me. Is that right?
What is the difference between *& and * as parameters?
Thank you for your time. I know there is a lot here.
First, am I on the right track?
A bit to general , let's go into details. But at least, you did not provide the required comments.
When using (char * a) for a function, for example, this is passing the address of a, correct?
No. It passes an address called a.
so then *artist=a; changes what the address of a points to?
This produces a type mismatch. artist is a pointer to char. *artist is the char variable artist points to. a is, agian, a pointer to char. So, you assign a pointer to a char variable => type mismatch.
Also, the functions are bool when I would expect void. Why?
I have no idea why do you expect void. However, bool makes sense: It allows the function to report, whether the operation (with side effect!) was successful or not.
For all of the set_xxx functions, the parameter is * ... but for
set_record_label it is *&. That appears to be a mistake to me. Is
that right?
Since your instructor stresses the use of different parameters, it is probably no error. However, in real life it would be a bad style.
What is the difference between *& and * as parameters?
* describes a pointer, & a reference. The referenced value can be a pointer again. I suggest that you reread the section on types in your textbook.

Question about var type

I am new to C# 3.0 var type. Here I have a question about this type. Take the following simple codes in a library as example:
public class MyClass {
public var Fn(var inValue)
{
if ( inValue < 0 )
{
return 1.0;
}
else
{
return inValue;
}
}
}
I think the parameter is an anonymous type. If I pass in a float value, then the Fn should return a float type. If a double value type is passed in, will the Fn return a double type? How about an integer value type as input value?
Actually, I would like to use var type with this function/method to get different return types with various input types dynamically. I am not sure if this usage is correct or not?
You can't use var for return values or parameter types (or fields). You can only use it for local variables.
Eric Lippert has a blog post about why you can't use it for fields. I'm not sure if there's a similar one for return values and parameter types. Parameter types certainly doesn't make much sense - where could the compiler infer the type from? Just what methods you try to call on the parameters? (Actually that's pretty much what F# does, but C# is more conservative.)
Don't forget that var is strictly static typing - it's just a way of getting the compiler to infer the static type for you. It's still just a single type, exactly as if you'd typed the name into the code. (Except of course with anonymous types you can't do that, which is one motivation for the feature.)
EDIT: For more details on var, you can download chapter 8 of C# in Depth for free at Manning's site - this includes the section on var. Obviously I hope you'll then want to buy the book, but there's no pressure :)
EDIT: To address your actual aim, you can very nearly implement all of this with a generic method:
public class MyClass
{
public T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
// This is the tricky bit.
return 1.0;
}
else
{
return inValue;
}
}
}
As shown in the listing, the tricky bit is working out what "1" means for an arbitrary type. You could hard code a set of values, but it's a bit ugly:
public class MyClass
{
private static readonly Dictionary<Type, object> OneValues
= new Dictionary<Type, object>
{
{ typeof(int), 1 },
{ typeof(long), 1L },
{ typeof(double), 1.0d },
{ typeof(float), 1.0f },
{ typeof(decimal), 1m },
};
public static T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
object one;
if (!OneValues.TryGetValue(typeof(T), out one))
{
// Not sure of the best exception to use here
throw new ArgumentException
("Unable to find appropriate 'one' value");
}
return (T) one;
}
else
{
return inValue;
}
}
}
Icky - but it'll work. Then you can write:
double x = MyClass.Fn(3.5d);
float y = MyClass.Fn(3.5f);
int z = MyClass.Fn(2);
etc
You cannot use var as a return type for a method.