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

coercion and context

Thread Next
From:
Juerd
Date:
September 14, 2005 14:38
Subject:
coercion and context
Message ID:
20050914213804.GQ12658@c4.convolution.nl
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
now.

my Int $int = $num;

Explicit coercion, however, isn't done with context: it is done with the
.as() method: $num.as(Int). 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
variable.

- 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.


Juerd
-- 
http://convolution.nl/maak_juerd_blij.html
http://convolution.nl/make_juerd_happy.html 
http://convolution.nl/gajigu_juerd_n.html

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About