From 8e3bb549b777438bf24c9f3213f63606b0d1ac4a Mon Sep 17 00:00:00 2001 From: Moritz Lenz Date: Thu, 12 Aug 2010 15:48:50 +0200 Subject: [PATCH] [blog] about cool --- source/blog-source-en/perl-6/cool.txt | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 source/blog-source-en/perl-6/cool.txt diff --git a/source/blog-source-en/perl-6/cool.txt b/source/blog-source-en/perl-6/cool.txt new file mode 100644 index 0000000..38ee6dc --- /dev/null +++ b/source/blog-source-en/perl-6/cool.txt @@ -0,0 +1,35 @@ +What is the "Cool" class in Perl 6? + + +

In Perl, subroutine and operator names determine what happens, usually not +the type of the arguments. Instead the arguments are coerced to a type on +which the operation makes sense:

+ +
[% syntax perl6 %]
+say uc 34;      # coerces 34 to a string, and upper-cases it
+say 1 + "2";    # converts "2" to a number before adding
+[% endsyntax %]
+ +

To make things more extensible, the uc function re-dispatches +to the uc method on its argument. So for the example above to +work, we need an uc function in Int. And in Array, so that +@a.uc works. And so on.

+ +

The original approach was to stuff all these methods into Any, +the base class of the object hierarchy. Which kinda worked, but also meant +that all user-defined classes ended up having some few hundreds methods to +start with. Not good.

+ +

These days, the type Cool fills this role: most built-in types +(all that are meant to be used in that polymorphic way) inherit from Cool, so +the uc method is actually defined in class Cool, +coerces to string, and then re-dispatches to the internal logic that actually +does the upper-casing.

+ +

If users want to write a type that can be used like a built-in type now +just inherit from Cool, and define coercion methods to other +built-in types. If the types don't inherit from Cool, they are +more light-weight, and less magic. There's more than one way to do it.

+ +[% option no-header %][% option no-footer %] +[% comment vim: set ft=html spell: %]