Skip to content

015 Classes

Petro Protsyk edited this page Aug 8, 2013 · 2 revisions

Classes

S# is not object-oriented language, however it is possible to emulated classes using property bags.

Function definition is a first class object in S#, which means it may be associated with a variable name, thus allowing to introduce functional logic as a part of property bag. Consider following example:

v = [
      x -> 4,
      y -> 3,
      length -> function() {
               Math.Sqrt(me.x^2+me.y^2);
      } 
    ];
l = v.length();

In the given example variable named 'length' is associated with anonymous function. This function calculates the length of the vector v. To get access to properties defined within current property bag, a function definition may use reserved name "me" (it is similar to C# this).

Here is yet more comprehensive example which shows implementation of 3x3 matrix class and matrix product function:

m = [
 //Rows
 r->3,
 //Columns
 c->3,
 //Values
 v->[1,2,3,
     4,5,6,
     7,8,9],

 //Get value 
 cell->function(row,col){
   return me.v[me.c*row + col];
 },

 //Set value
 set->function(row,col,val){
   me.v[me.c*row + col] = val;
 }
];

function MatProduct(a,b){
 rez = [
         r->a.r,
         c->b.c,
         v->new double[a.r*b.c],
         cell->a.cell,
         set->a.set
 ];

 for(i=0; i<a.r; i++){
   for (j=0; j<b.c; j++){
    s = 0;
    for (v=0; v<a.c; v++){
      s+= a.cell(i,v)*b.cell(v,j);
    } 
    rez.set(i,j,s);
   }
 }

 return rez;
}


r = MatProduct(m,m);
Clone this wiki locally