Got this class:
class Mass-lb is Mass {
method new(Rat:D() $value = 1.0) {
self.bless(
:abbr('lb'),
:base_value(453.59237),
:$value,
);
}
}
I have created aliases like this:
class Mass-lbs is Mass-lb { }
class Mass-pound is Mass-lb { }
class Mass-pounds is Mass-lb { }
class Mass-pnds is Mass-lb { }
But I'd prefer to do something like this:
my #lb-syn = < lbs pounds pound pnds >;
for #lb-syn {
EVAL 'class ::("Mass-$_") is Mass-lb {}';
}
This throws an error:
Name ::("Mass-$_") is not compile-time known, and can not serve as a package name
PHP has a built-in for creating aliases: https://www.php.net/manual/en/function.class-alias.php
I couldn't find anything similar for raku.
In RakuAST there's a class that you can call to create a new type. But that the RakuAST branch hasn't landed yet.
Until then, your approach using EVAL is valid, you just need to make it a bit simpler:
class Mass-lb { }
BEGIN "constant Mass-$_ = Mass-lb".EVAL
for <lbs pounds pound pnds>;
my $mlb = Mass-lbs.new;
Make sure the aliases are created at BEGIN time.
No need to subclass, you can use a constant for aliasing.
Since constants are our by default, they're visible outside of the EVAL.
Alternatively, you could use raku Physics::Unit and Physics::Measure...
use Physics::Unit;
use Physics::Measure :ALL;
# define a new custom Unit
Unit.new( defn => 'lbm', names => <Mass-lb Mass-lbs Mass-pound Mass-pounds Mass-pnds> );
say GetUnit('Mass-lbs').names; #[Mass-lb Mass-lbs Mass-pound Mass-pounds Mass-pnds]
# use the Unit in a Measure
my $mass = ♎️'42 Mass-pnds';
say $mass; #42Mass-lb
say $mass.^name; #(..Mass) ...class name
# convert to another Unit
my $kgm = $mass.in: 'kg';
say $kgm; #19.05087954kg
# convert back
say $kgm.in: 'Mass-pound'; #42Mass-lb
# raku Rats mean that the back conversion is identical
say $kgm cmp $mass; #Same
# with % or abs Error
my $mass2 = ♎️'42 Mass-pnds ±3%';
say $mass2; #42Mass-lb ±1.26
say $mass2.in: 'kg'; #19.05087954kg ±0.5715263862
More info at github Physics::Unit and Physics::Measure...
Is there a sensible way to have one perl6 module check for the presence of another perl6 module and to 'use' it if and only if it is installed?
Something like this...
module Polygons;
if $available {
use Measure; #only if Measure is installed
}
class Rectangle is export {
has $.width;
has $.height;
method area {
$!width * $!height; #provides operator overload for Measure * Measure
}
}
#====================
module Measure;
class Measure is export {
has $.value;
has $.unit;
method Real {
$!value;
}
method Str {
"$!value $!unit";
}
method multiply( $argument ) {
my $result = $.;
$result.value = $!value * $argument;
$result.unit = "$!unit2";
return $result;
}
}
multi infix:<*> ( Measure:D $left, Measure:D $right ) is export {
return $result.multiply( $argument );
}
#====================
#main.p6
use Polygons;
use Measure;
my $x = Measure.new( value => 10, unit => 'm' );
my $y = Measure.new( value => 20, unit => 'm' );
my $rect = Rectangle.new( width => $x, height => y );
say $rect.area; #'200 m2'
The idea is to propagate the operator overload (infix:<*> in this case) back up the class inheritance so that one store more elaborate objects in the attributes.
(Without tearing up the drains please - since I suspect there is always a way!)
So the first version of this answer was essentially useless.
Here's the first new thing I've come up with that works with what I understand your problem to be. I haven't tried it on the repo yet.
In a file a-module.pm6:
unit module a-module;
our sub infix:<*> ($l,$r) { $l + $r } }
The our means we'll be able to see this routine if we can require it, though it'll only be visible via its fully qualified name &a-module::infix:<*>.
Then in a using file:
use lib '.';
try require a-module;
my &infix:<*> = &a-module::infix:<*> // &OUTER::infix:<*>;
say 1 * 2 # 2 or 3 depending on whether `a-module.pm6` is found
The default routine used if the module is missing can be the one from OUTER (as shown) or from CALLER or whatever other pseudo package you prefer.
This problem/solution seems so basic I suspect it must be on SO or in the doc somewhere. I'll publish what I've got then explore more tomorrow.
Is there an actionscript library providing a queuing system?
This system would have to allow me to pass the object, the function I want to invoke on it and the arguments, something like:
Queue.push(Object, function_to_invoke, array_of_arguments)
Alternatively, is it possible to (de-)serialize a function call? How would I evaluate the 'function_to_invoke' with the given arguments?
Thanks in advance for your help.
There's no specific queue or stack type data structure available in ActionScript 3.0 but you may be able to find a library (CasaLib perhaps) that provides something along those lines.
The following snippet should work for you but you should be aware that since it references the function name by string, you won't get any helpful compiler errors if the reference is incorrect.
The example makes use of the rest parameter which allows you to specify an array of arbitrary length as the arguments for your method.
function test(... args):void
{
trace(args);
}
var queue:Array = [];
queue.push({target: this, func: "test", args: [1, 2, "hello world"] });
queue.push({target: this, func: "test", args: ["apple", "pear", "hello world"] });
for (var i:int = 0; i < queue.length; i ++)
{
var queued:Object = queue[i];
queued.target[queued.func].apply(null, queued.args);
}
Sure, that works similar to JavaScript
const name:String = 'addChild'
, container:Sprite = new Sprite()
, method:Function = container.hasOwnProperty(name) ? container[name] : null
, child:Sprite = new Sprite();
if (method)
method.apply(this, [child]);
So a query method could look like:
function queryFor(name:String, scope:*, args:Array = null):void
{
const method:Function = scope && name && scope.hasOwnProperty(name) ? scope[name] : null
if (method)
method.apply(this, args);
}
I'm a R-newbie, and I was wondering if it is possible to create objects of own classes. When I read the "help(class)" it did not seem that classes like in Java are possible. I mean I want to have a class with methods, private variables and a constructor. For example it could look like this:
className <- class {
# private variables
var1 <- "standardvalue"
var2 <- TRUE
# Constructor
constructor (v1, v2) {
var1 <- v1
var2 <- v2
}
# Method 1
function sum() {
var1 + var2
}
# Method 2
function product() {
var1 * var2
}
}
In my main programm I want to create an Object of this Class and call it's functions. For example like this:
# Create Object
numbers <- className(10,7)
# Call functions of the Object
numbers -> sum() # Should give "17"
numbers -> product() # Should give "70"
Is something like this possible? So far I did not fine any example.
Thanks for your help.
Yes, there are (at least) three OO systems to choose from in base R:
S3
S4
ReferenceClasses
plus additional OO-like frameworks contributed via CRAN packages such as proto.
Please do some googling for S3, S4, ReferenceClasses, OO, ..., possibly starting at rseek.org. All R programming books cover this too; my favourite is Chambers (2008) book titled "Software for Data Analysis".
If you come from java and therefore are used to private and public attributes and methods I'd advise you to use the R6 package. See this link. A trivial example of a person class taken from the documentation is this:
library(R6)
Person <- R6Class("Person",
public = list(
name = NA,
hair = NA,
initialize = function(name, hair) {
if (!missing(name)) self$name <- name
if (!missing(hair)) self$hair <- hair
self$greet()
},
set_hair = function(val) {
self$hair <- val
},
greet = function() {
cat(paste0("Hello, my name is ", self$name, ".\n"))
}
)
)
Here's how you can create an instance of this class:
johnDoe <- Person$new("John Doe")
johnDoe$set_hair("brown")
Note that unlike java methods are invoked using the $ operator after the object.
Does somebody know how to make private, non-static members in CoffeeScript? Currently I'm doing this, which just uses a public variable starting with an underscore to clarify that it shouldn't be used outside of the class:
class Thing extends EventEmitter
constructor: (#_name) ->
getName: -> #_name
Putting the variable in the class makes it a static member, but how can I make it non-static? Is it even possible without getting "fancy"?
classes are just functions so they create scopes. everything defined inside this scope won't be visible from the outside.
class Foo
# this will be our private method. it is invisible
# outside of the current scope
foo = -> "foo"
# this will be our public method.
# note that it is defined with ':' and not '='
# '=' creates a *local* variable
# : adds a property to the class prototype
bar: -> foo()
c = new Foo
# this will return "foo"
c.bar()
# this will crash
c.foo
coffeescript compiles this into the following:
(function() {
var Foo, c;
Foo = (function() {
var foo;
function Foo() {}
foo = function() {
return "foo";
};
Foo.prototype.bar = function() {
return foo();
};
return Foo;
})();
c = new Foo;
c.bar();
c.foo();
}).call(this);
Is it even possible without getting "fancy"?
Sad to say, you'd have to be fancy.
class Thing extends EventEmitter
constructor: (name) ->
#getName = -> name
Remember, "It's just JavaScript."
I'd like to show something even fancier
class Thing extends EventEmitter
constructor: ( nm) ->
_name = nm
Object.defineProperty #, 'name',
get: ->
_name
set: (val) ->
_name = val
enumerable: true
configurable: true
Now you can do
t = new Thing( 'Dropin')
# members can be accessed like properties with the protection from getter/setter functions!
t.name = 'Dragout'
console.log t.name
# no way to access the private member
console.log t._name
There is one problem with Vitaly's answer and that is you cannot define variables that you want to be unique to the scope, if you made a private name that way and then changed it, the name value would change for every single instance of the class, so there is one way we can solve that problem
# create a function that will pretend to be our class
MyClass = ->
# this has created a new scope
# define our private varibles
names = ['joe', 'jerry']
# the names array will be different for every single instance of the class
# so that solves our problem
# define our REAL class
class InnerMyClass
# test function
getNames: ->
return names;
# return new instance of our class
new InnerMyClass
It's not impossible to access the the names array from outside unless you use getNames
Test this out
test = new MyClass;
tempNames = test.getNames()
tempNames # is ['joe', 'jerry']
# add a new value
tempNames.push 'john'
# now get the names again
newNames = test.getNames();
# the value of newNames is now
['joe', 'jerry', 'john']
# now to check a new instance has a new clean names array
newInstance = new MyClass
newInstance.getNames() # === ['joe', 'jerry']
# test should not be affected
test.getNames() # === ['joe', 'jerry', 'john']
Compiled Javascript
var MyClass;
MyClass = function() {
var names;
names = ['joe', 'jerry'];
MyClass = (function() {
MyClass.name = 'MyClass';
function MyClass() {}
MyClass.prototype.getNames = function() {
return names;
};
return MyClass;
})();
return new MyClass;
};
Here is a solution that draws on several of the other answers here plus https://stackoverflow.com/a/7579956/1484513. It stores the private instance (non-static) variables in a private class (static) array and uses an object ID to know which element of that array contains the data belonging to each instance.
# Add IDs to classes.
(->
i = 1
Object.defineProperty Object.prototype, "__id", { writable:true }
Object.defineProperty Object.prototype, "_id", { get: -> #__id ?= i++ }
)()
class MyClass
# Private attribute storage.
__ = []
# Private class (static) variables.
_a = null
_b = null
# Public instance attributes.
c: null
# Private functions.
_getA = -> a
# Public methods.
getB: -> _b
getD: -> __[#._id].d
constructor: (a,b,#c,d) ->
_a = a
_b = b
# Private instance attributes.
__[#._id] = {d:d}
# Test
test1 = new MyClass 's', 't', 'u', 'v'
console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 t u v
test2 = new MyClass 'W', 'X', 'Y', 'Z'
console.log 'test2', test2.getB(), test2.c, test2.getD() # test2 X Y Z
console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 X u v
console.log test1.a # undefined
console.log test1._a # undefined
# Test sub-classes.
class AnotherClass extends MyClass
test1 = new AnotherClass 's', 't', 'u', 'v'
console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 t u v
test2 = new AnotherClass 'W', 'X', 'Y', 'Z'
console.log 'test2', test2.getB(), test2.c, test2.getD() # test2 X Y Z
console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 X u v
console.log test1.a # undefined
console.log test1._a # undefined
console.log test1.getA() # fatal error
Here's the best article I found about setting public static members, private static members, public and private members, and some other related stuff. It covers much details and js vs. coffee comparison. And for the historical reasons here's the best code example from it:
# CoffeeScript
class Square
# private static variable
counter = 0
# private static method
countInstance = ->
counter++; return
# public static method
#instanceCount = ->
counter
constructor: (side) ->
countInstance()
# side is already a private variable,
# we define a private variable `self` to avoid evil `this`
self = this
# private method
logChange = ->
console.log "Side is set to #{side}"
# public methods
self.setSide = (v) ->
side = v
logChange()
self.area = ->
side * side
s1 = new Square(2)
console.log s1.area() # output 4
s2 = new Square(3)
console.log s2.area() # output 9
s2.setSide 4 # output Side is set to 4
console.log s2.area() # output 16
console.log Square.instanceCount() # output 2
Here is how you can declare private, non-static members in Coffeescript
For full reference, you can take a look at https://github.com/vhmh2005/jsClass
class Class
# private members
# note: '=' is used to define private members
# naming convention for private members is _camelCase
_privateProperty = 0
_privateMethod = (value) ->
_privateProperty = value
return
# example of _privateProperty set up in class constructor
constructor: (privateProperty, #publicProperty) ->
_privateProperty = privateProperty
"class" in coffee scripts leads to an prototype based result. So even if you use a private variable it is shared between instances. You can do this:
EventEmitter = ->
privateName = ""
setName: (name) -> privateName = name
getName: -> privateName
.. leads to
emitter1 = new EventEmitter()
emitter1.setName 'Name1'
emitter2 = new EventEmitter()
emitter2.setName 'Name2'
console.log emitter1.getName() # 'Name1'
console.log emitter2.getName() # 'Name2'
But be careful to put the private members before the public functions, because coffee script returns the public functions as object. Look at the compiled Javascript:
EventEmitter = function() {
var privateName = "";
return {
setName: function(name) {
return privateName = name;
},
getName: function() {
return privateName;
}
};
};
Since coffee script compiles down to JavaScript the only way you can have private variables is through closures.
class Animal
foo = 2 # declare it inside the class so all prototypes share it through closure
constructor: (value) ->
foo = value
test: (meters) ->
alert foo
e = new Animal(5);
e.test() # 5
This will compile down through the following JavaScript:
var Animal, e;
Animal = (function() {
var foo; // closured by test and the constructor
foo = 2;
function Animal(value) {
foo = value;
}
Animal.prototype.test = function(meters) {
return alert(foo);
};
return Animal;
})();
e = new Animal(5);
e.test(); // 5
Of course this has all the same limitations as all the other private variables you can have through the use of closures, for example, newly added methods don't have access to them since they were not defined in the same scope.
You can't do it easily with CoffeeScript classes, because they use the Javascript constructor pattern for creating classes.
However, you could say something like this:
callMe = (f) -> f()
extend = (a, b) -> a[m] = b[m] for m of b; a
class superclass
constructor: (#extra) ->
method: (x) -> alert "hello world! #{x}#{#extra}"
subclass = (args...) -> extend (new superclass args...), callMe ->
privateVar = 1
getter: -> privateVar
setter: (newVal) -> privateVar = newVal
method2: (x) -> #method "#{x} foo and "
instance = subclass 'bar'
instance.setter 123
instance2 = subclass 'baz'
instance2.setter 432
instance.method2 "#{instance.getter()} <-> #{instance2.getter()} ! also, "
alert "but: #{instance.privateVar} <-> #{instance2.privateVar}"
But you lose the greatness of CoffeeScript classes, because you can't inherit from a class created that way by any other way than by using extend() again. instanceof will stop working, and objecs created this way consume a little bit more memory. Also, you mustn't use the new and super keywords anymore.
The point is, that the closures must be created every time a class is instantiated. The member closures in pure CoffeeScript classes are created only once - that is, when the class runtime "type" is constructed.
If you want only separate private memebers from public, just wrap it in $ variable
$:
requirements:
{}
body: null
definitions: null
and use #$.requirements