develooper Front page | perl.perl6.language | Postings from September 2005

coercion and context

Thread Next
September 14, 2005 14:38
coercion and context
Message ID:
I was asked to { Verb 'p6l' } the idea of types providing context, and
well, here it is.

(We got at these thoughts from a discussion of a hypothetic lexical pragma
to disable automatic coercion, which I thought was a bad idea because
that's practically to ignore context, Perl's strongest language feature
(imo). Instead, if you don't want something to coerce, be explicit:
$foo.does(Blah) or fail;, or even: $foo.isa(Blah) or fail;.)

Some types can coerce into eachother. This happens transparently because
of context. The simplest example I can think of is a Num, that in Int
context is coerced to an int. Lossily, but that's not my point right

my Int $int = $num;

Explicit coercion, however, isn't done with context: it is done with the
.as() method: $ I think that's weird.

Why not see "bare" types as functions that create context? We'd then
have Int $num, Int($num), and automatically, $num.Int. All are easy to
recognise because of the capital I.

Is this weird syntax? Perhaps so, but we've known it from undef for
ages. undef without arguments is just undef, but when you give it
arguments, it suddenly actually *does* something.

undef($foo) makes $foo undef, undef() just returns undef.

Compare with:

Int($foo) makes $foo Int, Int() just returns ::Int.

Of course, for this comparison to work, undef would have to be a type.
Which makes having interisting undefs easier: they'd be parametrized
types. And undef could simply provide undef context, in which every
scalar coerces to... undef. But mutating, of course. I don't think it
would be a problem to have undef be a little special. ucfirst Undef
could be a non-mutating form, if consistency here is important.

Miscellaneous remarks:

- There would no longer be a need for int(), as Int() suffices. I'm
assuming that you only get to have a system native value in a typed

- The reason for having both Scalar() and item() is that Scalar()
coerces: afterwards, a Num is no longer a Num.

- We agreed that there have to be two ways (at least) to test for
ability to coerce, as this can happen lossily and losslessly. Thinks
like $foo.canbe(Int) and $foo.fitsin(Int) came to mind, but single word
method names are probably better, if only someone can think of any.


Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About