Abstract type: Difference between revisions

Content added Content deleted
(Nimrod -> Nim)
(→‎{{header|Lua}}: Appended Mathematica solution)
Line 1,085: Line 1,085:
B:new() -- Error: B is abstract
B:new() -- Error: B is abstract
BB:new() -- Okay: BB is not abstract</lang>
BB:new() -- Okay: BB is not abstract</lang>


=={{header|Mathematica}}==

Mathematica is a symbolic language and as such does not support traditional object oriented design patterns. However, it is quite easy to define pseudo-interfaces that depend on an object implementing a set of functions:

<lang Mathematica>
(* Define an interface, Foo, which requires that the functions Foo, Bar, and Baz be defined *)
InterfaceFooQ[obj_] := ValueQ[Foo[obj]] && ValueQ[Bar[obj]] && ValueQ[Baz[obj]];
PrintFoo[obj_] := Print["Object ", obj, " does not implement interface Foo."];
PrintFoo[obj_?InterfaceFooQ] := Print[
"Foo: ", Foo[obj], "\n",
"Bar: ", Bar[obj], "\n",
"Baz: ", Baz[obj], "\n"];

(* Extend all integers with Interface Foo *)
Foo[x_Integer] := Mod[x, 2];
Bar[x_Integer] := Mod[x, 3];
Baz[x_Integer] := Mod[x, 5];

(* Extend a particular string with Interface Foo *)
Foo["Qux"] = "foo";
Bar["Qux"] = "bar";
Baz["Qux"] = "baz";

(* Print a non-interface object *)
PrintFoo[{"Some", "List"}];
(* And for an integer *)
PrintFoo[8];
(* And for the specific string *)
PrintFoo["Qux"];
(* And finally a non-specific string *)
PrintFoo["foobarbaz"]
</lang>
{{out}}
<pre>
Object {Some,List} does not implement interface Foo.

Foo: 0
Bar: 2
Baz: 3

Foo: foo
Bar: bar
Baz: baz

Object foobarbaz does not implement interface Foo.
</pre>

Note that, in this implementation, the line between interface and abstract type is blurred. It could be argued that PrintFoo[] is a concrete member of the abstract type InterfaceFoo, or that it's a separate function that accepts anything implementing the interface InterfaceFoo.


=={{header|Nemerle}}==
=={{header|Nemerle}}==