Constrained genericity: Difference between revisions

Content deleted Content added
cat:type system
→‎{{header|Scala}}: ++ sather, hopefully I've taken it right
Line 316: Line 316:
let your_box = FloatBox.make_box_from_list [2.3; 4.5]</lang>
let your_box = FloatBox.make_box_from_list [2.3; 4.5]</lang>
Unfortunately, it is kind of cumbersome in that, for every type parameter we want to use for this generic type, we will have to explicitly create a module for the resulting type (i.e. <tt>BananaBox</tt>, <tt>FloatBox</tt>). And the operations on that resulting type (i.e. <tt>make_box_from_list</tt>) are tied to each specific module.
Unfortunately, it is kind of cumbersome in that, for every type parameter we want to use for this generic type, we will have to explicitly create a module for the resulting type (i.e. <tt>BananaBox</tt>, <tt>FloatBox</tt>). And the operations on that resulting type (i.e. <tt>make_box_from_list</tt>) are tied to each specific module.

=={{header|Sather}}==
<lang sather>abstract class $EDIBLE is
eat;
end;

class FOOD < $EDIBLE is
readonly attr name:STR;
eat is
#OUT + "eating " + self.name + "\n";
end;
create(name:STR):SAME is
res ::= new;
res.name := name;
return res;
end;
end;

class CAR is
readonly attr name:STR;
create(name:STR):SAME is
res ::= new;
res.name := name;
return res;
end;
end;

class FOODBOX{T < $EDIBLE} is
private attr list:LLIST{T};
create:SAME is
res ::= new;
res.list := #;
return res;
end;
add(c :T) is
self.list.insert_back(c);
end;
elt!:T is loop yield self.list.elt!; end; end;
end;

class MAIN is
main is
box ::= #FOODBOX{FOOD}; -- ok
box.add(#FOOD("Banana"));
box.add(#FOOD("Amanita Muscaria"));

box2 ::= #FOODBOX{CAR}; -- not ok
box2.add(#CAR("Punto")); -- but compiler let it pass!

-- eat everything
loop box.elt!.eat; end;
end;
end;</lang>

The GNU Sather compiler v1.2.3 let the "box2" pass, even though it shouldn't. Read e.g. [http://www.gnu.org/software/sather/docs-1.2/tutorial/parameterized1751.html this tutorial's section]


=={{header|Scala}}==
=={{header|Scala}}==