eval should throw an exception on compile error

2011-05-06 Thread Michael G Schwern
I was just playing around with eval, trying to figure out if you can define an
operator overload at runtime (seems you can't, good) and noticed this in the
spec... [1]

Returns whatever $code returns, or fails.

How does one get the compile error from an eval?  What's the equivalent to $@?
 I don't see anything in the eval tests [2] that's checking for the error,
just that it returned false.

In addition, I'm surprised that eval doesn't throw an error when it fails.

try { eval $code; CATCH { ... } }

Using eval STRING in Perl 5 is pretty rare, and should hopefully be rarer in
Perl 6 than Perl 5.  While it can be used as a does this compile check, it's
overwhelmingly used with the expectation that the code will compile and so it
is an exception if it does not.  More pragmatically, this resolves the problem
of $@ by putting it into an exception rather than a side global.

It also resolves this trap:

if eval $code {
say code returned true;
}
else {
# this will also happen if $code fails to compile
say code returned false;
}

While Perl 6 probably has some sort of magic I failed value you can check
for separate from boolean false, folks aren't going to go through the extra
convolutions.


[1] http://perlcabal.org/syn/S29.html
[2] https://github.com/perl6/roast/blob/master/S29-context/eval.t

-- 
31. Not allowed to let sock puppets take responsibility for any of my
actions.
-- The 213 Things Skippy Is No Longer Allowed To Do In The U.S. Army
   http://skippyslist.com/list/



Re: Smooth numeric upgrades?

2008-10-06 Thread Michael G Schwern
So, the concrete use-case I'm thinking of here is currency.


Darren Duncan wrote:
 [2] Num should have an optional limit on the number of decimal places
 it remembers, like NUMERIC in SQL, but that's a simple truncation.
 
 I disagree.
 
 For starters, any limit built into a type definition should be defined
 not as stated above but rather with a simple subtype declaration, eg
 subtype of Rat where ... that tests for example that the Rat is an
 exact multiple of 1/1000.
 
 Second, any truncation should be done at the operator level not at the
 type level; for example, the rational division operator could have an
 optional extra argument that says the result must be rounded to be an
 exact multiple of 1/1000; without the extra argument, the division
 doesn't truncate anything.
 
 Any numeric operations that would return an irrational number in the
 general case, such as sqrt() and sin(), and the user desires the result
 to be truncated to an exact rational number rather than as a symbolic
 number, then those operators should have an extra argument that
 specifies rounding, eg to an exact multiple of 1/1000.

That seems like scattering a lot of redundant extra arguments around.  The
nice thing about doing it as part of the type is you just specify it once.

But instead of truncating data in the type, maybe what I want is to leave the
full accuracy inside and instead override string/numification to display only
2 decimal places.

But sometimes I want to hang onto fractional pennies and use them in
calculation, just hide them from view.  And sometimes I don't.


 Note, a generic numeric rounding operator would also take the exact
 multiple of argument rather than a number of digits argument, except
 when that operator is simply rounding to an integer, in which case no
 such argument is applicable.
 
 Note, for extra determinism and flexibility, any operation
 rounding/truncating to a rational would also take an optional argument
 specifying the rounding method, eg so users can choose between the likes
 of half-up, to-even, to-zero, etc.  Then Perl can easily copy any
 semantics a user desires, including when code is ported from other
 languages and wants to maintain exact semantics.

Yes, this is very important for currency operations.


 Now, as I see it, if Num has any purpose apart from Rat, it would be
 like a whatever numeric type or effectively a union of the
 Int|Rat|that-symbolic-number-type|etc types, for people that just want
 to accept numbers from somewhere and don't care about the exact
 semantics.  The actual underlying type used in any given situation would
 determine the exact semantics.  So Int and Rat would be exact and
 unlimited precision, and maybe Symbolic or IRat or something would be
 the symbolic number type, also with exact precision components.

That sounds right.  It's the whatever can conceivably be called a number type.



-- 
44. I am not the atheist chaplain.
-- The 213 Things Skippy Is No Longer Allowed To Do In The U.S. Army
   http://skippyslist.com/list/


Re: Smooth numeric upgrades?

2008-10-05 Thread Michael G Schwern
Darren Duncan wrote:
 Patrick R. Michaud wrote:
 Correct.  I suspect that eventually the Rakudo developers will have
 to develop a custom set of PMCs for Perl 6 behaviors rather than
 relying on the Parrot ones.
 
 I think it would be better for things like unlimited-precision integers
 and rationals to be Parrot generic PMCs rather than Perl 6 specific
 ones, since there are other languages that also have unlimited-precision
 numbers (for example Python afaik) and it would be better to have a
 common implementation.  Several popular languages have unlimiteds now,
 and more are coming over time.

+1

The basics of sane numbers should be pushed down into Parrot.
(Of course, my vote counts for bupkis as I'm not going to be the one to
implement it)


-- 
Whip me, beat me, make my code compatible with VMS!


Re: [svn:perl6-synopsis] r14585 - doc/trunk/design/syn

2008-10-05 Thread Michael G Schwern
TSa (Thomas Sandlaß) wrote:
 Can't we have that as a general feature of all operators?
 That is:
 
my ($x, $y);
 
say $x * $y; # prints 1
say $x + $y; # prints 0
 
 It is a cleaver idea to make the operator choose an appropriate
 value for a Nothing value. Why having that only for meta operators?

Because it throws out the utility of the undefined value warning as a way to
catch mistakes.

Why special case increment and decrement?  Two reasons IMO.  Incrementing has
a very narrow use case and it's pretty hard to screw up.

Second is that it's really annoying if you don't.  Try working in Javascript
which doesn't.  You find yourself doing input ||= 0 a lot... except oh wait
you can't do that because ||= doesn't work on undef in Javascript.  This is
the best I've come up with. [1] [2]

input = (input || 0);

Point is, certain op= quietly treating undef as 0 avoids yucky constructs to
appease fussy compilers.  The rest, leave alone so the undef warning can do
its job.


[1] I am not a Javascript programmer, but I haven't seen anything better.

[2] Nevermind there's not a proper defined check in there.  That would be
  input = input === null ? input : 0;
but most languages don't have a built in dor operator so we won't
penalize Javascript for that.


-- 
185. My name is not a killing word.
-- The 213 Things Skippy Is No Longer Allowed To Do In The U.S. Army
   http://skippyslist.com/list/


Re: Smooth numeric upgrades?

2008-10-05 Thread Michael G Schwern
TSa (Thomas Sandlaß) wrote:
 I want to stress this last point. We have the three types Int, Rat and Num.
 What exactly is the purpose of Num? The IEEE formats will be handled
 by num64 and the like. Is it just there for holding properties? Or does
 it do some more advanced numeric stuff?

Int, Rat [1] and Num are all human types.  They work like humans were
taught numbers work in math class.  They have no size limits.  They shouldn't
lose accuracy. [2]

As soon as you imply that numbers have a size limit or lose accuracy you are
thinking like a computer.  That's why num64 is not a replacement for Num,
conceptually nor is int64 a replacement for Int.  They have limits and
lose accuracy.

Making Num just work like humans expect is the more advanced numeric stuff
I suppose. :)


[1] As a name Rat as the type which holds fractions is about as good
as Float to be the type which holds decimal numbers.  Gotta be
something that makes more sense to non CS people.  Like, say, Fraction.

[2] Num should have an optional limit on the number of decimal places
it remembers, like NUMERIC in SQL, but that's a simple truncation.


-- 
184. When operating a military vehicle I may *not* attempt something
 I saw in a cartoon.
-- The 213 Things Skippy Is No Longer Allowed To Do In The U.S. Army
   http://skippyslist.com/list/


Re: Smooth numeric upgrades?

2008-10-04 Thread Michael G Schwern
Larry Wall wrote:
 On Fri, Oct 03, 2008 at 11:57:30PM -0400, Michael G Schwern wrote:
 : What's the status of numeric upgrades in Perl 6?  Is see the docs say Perl 
 6
 : intrinsically supports big integers and rationals through its system of type
 : declarations. Int automatically supports promotion to arbitrary precision 
 but
 : it looks like it's doing the same thing as Perl 5.
 : 
 : $ ./perl6 -e 'say 2**40'
 : 1099511627776
 : 
 : $ ./perl6 -e 'say 2**50'
 : 1.12589990684262e+15
 : 
 : $ ./perl6 -e 'say 2**1100'
 : inf
 
 The status of numeric upgrades in Perl 6 is fine.  It's rakudo that
 doesn't do so well.  :)

 As another datapoint:
 
 $  pugs -e 'say 2**40'
 1099511627776
 $ pugs -e 'say 2**50'
 1125899906842624
 $ pugs -e 'say 2**1100'
 13582985290493858492773514283592667786034938469317445497485196697278130927542418487205392083207560592298578262953847383475038725543234929971155548342800628721885763499406390331782864144164680730766837160526223176512798435772129956553355286032203080380775759732320198985094884004069116123084147875437183658467465148948790552744165376

That's good [1] to hear, thanks.


 I don't think of Int as a type that automatically upgrades.  I think
 of it as an arbritrarily large integer that the implementation can in
 some cases choose to optimize to a smaller or faster representation,

Oh don't worry, I do.  I just got so flustered when I saw Rakudo do the same
thing that Perl 5 does I was worried this got lost somewhere along the line.


[1] We need a polite way to say less bad.


-- 
The mind is a terrible thing,
and it must be stopped.


Smooth numeric upgrades?

2008-10-03 Thread Michael G Schwern
What's the status of numeric upgrades in Perl 6?  Is see the docs say Perl 6
intrinsically supports big integers and rationals through its system of type
declarations. Int automatically supports promotion to arbitrary precision but
it looks like it's doing the same thing as Perl 5.

$ ./perl6 -e 'say 2**40'
1099511627776

$ ./perl6 -e 'say 2**50'
1.12589990684262e+15

$ ./perl6 -e 'say 2**1100'
inf

And...

$ ./perl6 -e 'my Int $foo = 2**32;  say $foo'
Type check failed
current instr.: 'parrot;Perl6Object;infix:=' pc 60 (src/gen_builtins.pir:52)
called from Sub '_block11' pc 98 (EVAL_12:41)
called from Sub 'parrot;PCT::HLLCompiler;eval' pc 806
(src/PCT/HLLCompiler.pir:480)
called from Sub 'parrot;PCT::HLLCompiler;command_line' pc 1298
(src/PCT/HLLCompiler.pir:707)
called from Sub 'parrot;Perl6::Compiler;main' pc 17029 (perl6.pir:172)
perl6(4325) malloc: ***  Deallocation of a pointer not malloced: 0x4157170;
This could be a double free(), or free() called with the middle of an
allocated block; Try setting environment variable MallocHelp to see tools to
help debug
perl6(4325) malloc: ***  Deallocation of a pointer not malloced: 0xda71b; This
could be a double free(), or free() called with the middle of an allocated
block; Try setting environment variable MallocHelp to see tools to help debug
Bus error (core dumped)

though hopefully that's transient.


-- 
Clutter and overload are not an attribute of information,
 they are failures of design
-- Edward Tufte



Re: Why no is ro? (Re: Subroutine parameter with trait and default.)

2008-09-25 Thread Michael G Schwern
David Green wrote:
 I bet we actually don't disagree much; I'm not really against ro --
 I'm just not against readonly because of its length.  If I were
 writing casually, I'd use rw and ro; formally, I'd use read only
 and read/write (or even readable and writable).  At an in-between
 level, which is where I believe we should be aiming, I think I'd put
 rw and read-only.  I'm not entirely sure why.  Maybe
 psychologically, ro looks like it could be a word, whereas the
 unpronounceable rw has to be an abbreviation?  Or maybe it's just
 because I see rw every day in ls output, but ro not so much.  At any
 rate, if I wanted to argue in favour of ro, I think symmetry (which
 you already mentioned) is the strongest argument.

Yes indeed, symmetry.  It's powerful.  Once you see rw you're going to
assume the other is ro.  Same with readonly and readwrite.  And
vice-versa and con-versa and any other versas you can think of.

rw/readonly is the worst choice.  It has that double wammy of bad interfaces:
 rote learning and counter-intuitiveness.  Not only do you have to memorize
that read-only is readonly and read/write is ro but you have to
actively fight your intuition that they should be symmetrical.  This generates
mistakes.  Constant mistakes.

rw/ro makes similar things similar.  So does readwrite/readonly.  Pick one of
them.  Asymmetry will cause far more problems than too little or too much
verbosity.


-- 
ROCKS FALL! EVERYONE DIES!
http://www.somethingpositive.net/sp05032002.shtml


Why no is ro? (Re: Subroutine parameter with trait and default.)

2008-09-23 Thread Michael G Schwern
John M. Dlugosz wrote:
 I'm not opposed to having it be ro, but wonder why he didn't call it that
 in the first place, so there must be a reason.

Nobody's perfect?

My other thought is that since parameters are read-only by default it's not
thought you'd have to write it much so clarity wins out over brevity, the flip
side of Huffamn encoding.  But that doesn't work out so good for normal
variable declarations.  The verbosity (which a hyphen would only make worse)
discourages const-ing, as they say in C.


 It should be possible to alias it in your own scope easily.

Every time someone replies to a Perl 6 language design nit with but you can
change the grammar *I* kill a kitten.

*meowmmmf*


-- 
31. Not allowed to let sock puppets take responsibility for any of my
actions.
-- The 213 Things Skippy Is No Longer Allowed To Do In The U.S. Army
   http://skippyslist.com/list/


Re: Why no is ro? (Re: Subroutine parameter with trait and default.)

2008-09-23 Thread Michael G Schwern
David Green wrote:
 On 2008-Sep-23, at 2:32 pm, Michael G Schwern wrote:
 My other thought is that since parameters are read-only by default
 it's not
 thought you'd have to write it much so clarity wins out over brevity,
 the flip
 side of Huffamn encoding.  But that doesn't work out so good for normal
 variable declarations.
 
 I'd call it straight Huffman encoding, because clarity is what we should
 be optimising for. (You read code more than you write it... unless you
 never make any mistakes!)  Happily, brevity often aids clarity.  The
 rest of the time, it should be up to one's editor; any editor worth its
 salt ought to easily auto-complete ro into readonly.

Eeep!  The your IDE should write your verbose code for you argument!  For
that one, I brine and roast an adorable hamster.  That's just another way of
saying that your language is too verbose for a human to write it without
hanging themselves.  See also Java.

Anyhow, I see where you're going, and I understand the desire for no abbvs.
But man, ro is pretty damn easy to remember. [1]  This is even sillier when
you hold it up against all the magic symbols we're supposed to remember.
[EMAIL PROTECTED], :namevalue, |$arg, $arg!, $arg?, :$arg.

If we expect the user to remember what all that means, I think they can figure
out $thing is ro.  It would be incoherent to take a corner of the language
design and suddenly pretend otherwise.

The mark of a great interface is not that you know what everything is the
first time you encounter it, but when you remember what it is the second time.
 The first time what's important is the user knows where to find instructions
and how to play with the device.  It should have a strong analogy and mesh
clearly with the surrounding devices ro and rw have a strong analogy with
the common read-only and read-write terms and they mesh with each other.  Once
this is known to the user, the second time it will be obvious.

You're only a beginner once, and if everything is done right for a short time.
 The rest of your career, you're experienced.  Instead of dumbing the language
down for beginners, the trick is to turn beginners into experienced
programmers as quickly and painlessly as possible.

Now I've totally digressed./rant


-- 
s7ank: i want to be one of those guys that types s/jjd//.^$ueu*///djsls/sm.
   and it's a perl script that turns dog crap into gold.


Re: Subroutine parameter with trait and default.

2008-09-22 Thread Michael G Schwern
Patrick R. Michaud wrote:
 On Sun, Sep 21, 2008 at 07:02:37PM -0700, Michael G Schwern wrote:
 I'm pondering what the proper syntax is for a subroutine parameter with both 
 a
 trait and a default.  That is...
  sub foo ($arg = 42)
 and
  sub foo ($arg is readonly)
 together in one parameter.  Would that be
  sub foo ($arg = 42 is readonly)
 or
  sub foo ($arg is readonly = 42)

 The first looks ambiguous, what if the trait is meant to apply to the 
 default?
 The second looks downright wrong.
 
 
 The STD.pm grammar [1] shows that the second is the correct form -- 
 i.e., default values occur after traits.  (See token parameter 
 on or about line 2630.)  I think part of the reason for this is that
 traits appearing after the default value would be applied to the
 default value instead of the parameter.  A few other examples from
 the synopses seem to confirm this pattern:
 
   S03:2289:my Dog $fido is trained is vicious = 1
   S03:3828:constant Dog $foo is woof = 123;
   S06:1558:constant $pi is approximated = 3;
   S12:1393:has SomeType $.prop is rw = 1;
 
 1.  http://svn.pugscode.org/pugs/src/perl6/STD.pm

Ok, thanks.  That does make sense.


 PS  Incidentally, it seems silly to have is rw but not is ro.  I keep
 writing is ro.
 
 Yes, we've also run into this problem a few times while working on Rakudo.

I'm finding it so verbose that I'm going with is ro in Method::Signatures.


-- 
I'm pale as formica, social skills stunted small. But I'm accurate
like a pica, I know the capital of nepal. I'm the nemesis of error,
dreadful diction fears my skills, more inquisitive than Jim Lehrer,
snottier than Beverly Hills.
-- I.L.O.P. Secret Rap  http://goats.com/archive/020830.html


Subroutine parameter with trait and default.

2008-09-21 Thread Michael G Schwern
I'm pondering what the proper syntax is for a subroutine parameter with both a
trait and a default.  That is...

sub foo ($arg = 42)

and

sub foo ($arg is readonly)

together in one parameter.  Would that be

sub foo ($arg = 42 is readonly)

or

sub foo ($arg is readonly = 42)

The first looks ambiguous, what if the trait is meant to apply to the default?
The second looks downright wrong.


PS  Incidentally, it seems silly to have is rw but not is ro.  I keep
writing is ro.


-- 
package Outer::Space;  use Test::More tests = 9;



Re: Deep equivalence test of data structures

2008-09-14 Thread Michael G Schwern
Eric Wilhelm asked me to chime in here.

is_deeply() is about checking that two structures contain the same values.
This is different from checking that they're the same *things*, that they are
in fact the same object or reference.

You need both.

Reading eqv() it seems that yes, it is doing like is_deeply() does and just
cares about the values.

So yes, by my reading Patrick is right, [1,2,3] eqv [1,2,3] should be true.

S03 says:
the eqv operator tests whether the canonical representation of both subvalues
would be identical

and that's really useful.

One thing that isn't addressed is what happens to objects?  For example, the
following passes with is_deeply()...

my $obj = bless [1,2,3], Foo;
is_deeply( $obj, [1,2,3] );

but that's just because it's convenient for testing and the Perl 5 objects
are just references thing.  I understand that objects can define their own
eqv() functions, but a good default would seem to be that if one is a subclass
of the other, that's ok.

And here's the annotated spec test.

# Reference types
{
  my @a = (1,2,3);
  my @b = (1,2,3);

  ok  ([EMAIL PROTECTED] eqv [EMAIL PROTECTED]), eqv on array 
references (1);
  ok  ([EMAIL PROTECTED] eqv [EMAIL PROTECTED]), eqv on array 
references (2);
  #?pugs todo 'bug'
  ok !([EMAIL PROTECTED] eqv [EMAIL PROTECTED]), eqv on array 
references (3); # wrong
}

{
  my $a = \3;
  my $b = \3;

  ok  ($a eqv $a), eqv on scalar references (1-1);
  ok  ($b eqv $b), eqv on scalar references (1-2);
  #?pugs todo 'bug'
  ok !($a eqv $b), eqv on scalar references (1-3);# wrong
}

{
  my $a = { 3 };
  my $b = { 3 };

  ok  ($a eqv $a), eqv on sub references (1-1);
  ok  ($b eqv $b), eqv on sub references (1-2);
  ok !($a eqv $b), eqv on sub references (1-3);   # wrong
}

{
  ok  (say eqv say), eqv on sub references (2-1);
  ok  (map eqv map), eqv on sub references (2-2);
  ok !(say eqv map), eqv on sub references (2-3);
}

{
  my $num = 3;
  my $a   = \$num;
  my $b   = \$num;

  ok  ($a eqv $a), eqv on scalar references (2-1);
  ok  ($b eqv $b), eqv on scalar references (2-2);
  ok  ($a eqv $b), eqv on scalar references (2-3);
}

{
  ok !([1,2,3] eqv [4,5,6]), eqv on anonymous array references (1);
  #?pugs 2 todo 'bug'
wrong ok !([1,2,3] eqv [1,2,3]), eqv on anonymous array references (2);
wrong ok !([]  eqv []),  eqv on anonymous array references (3);
}

{
  ok !({a = 1} eqv {a = 2}), eqv on anonymous hash references (1);
wrong ok !({a = 1} eqv {a = 1}), eqv on anonymous hash references (2);
}

{
  ok !(\3 eqv \4), eqv on anonymous scalar references (1);
  #?pugs 2 todo 'bug'
wrong ok !(\3 eqv \3), eqv on anonymous scalar references (2);
wrong ok !(\undef eqv \undef), eqv on anonymous scalar references (3);
}

# Chained eqv (not specced, but obvious)
{
  ok  (3 eqv 3 eqv 3), chained eqv (1);
  ok !(3 eqv 3 eqv 4), chained eqv (2);
}

# Subparam binding doesn't affect eqv test
{
  my $foo;
  my $test = - $arg { $foo eqv $arg };

  $foo = 3;
  ok  $test($foo), subparam binding doesn't affect eqv (1);
  ok  $test(3),subparam binding doesn't affect eqv (2);

  ok !$test(4),subparam binding doesn't affect eqv (3);
  my $bar = 4;
  ok !$test($bar), subparam binding doesn't affect eqv (4);
}

{
is(1 eqv 1, Bool::True,  'eqv returns Bool::True when true');
is(0 eqv 1, Bool::False, 'eqv returns Bool::False when false');
}


Patrick R. Michaud wrote:
 On Sun, Sep 14, 2008 at 03:08:57PM +0200, Carl Mäsak wrote:
 Recently, in November, we've had reason to clone the Rakudo Test.pm
 and add an implementation (viklund++) of is_deeply, for testing
 whether two arrays, pairs or hashes are deeply -- recursively --
 equivalent. The method does what you'd think it does, checks the types
 of its parameters and recurses as necessary.

 With the rich set of equality testing operators in Perl 6...

  http://www.dlugosz.com/Perl6/web/eqv.html
  http://perlcabal.org/syn/S03.html#Comparison_semantics

 ...and given constructs like [+] and +, it's actually a bit
 surprising to me that testing whether [1, [2, 3]] and [1, [2, 4]] are
 the deeply equivalent isn't more easily expressed than it is. (Or
 maybe it is easy with current constructs, and I missed it? Can't rule
 that out.)

 Couldn't an adverb to one or more of the existing 

Re: Concerns about {...code...}

2007-12-21 Thread Michael G Schwern
John Siracusa wrote:
 On 12/21/07 5:54 AM, Larry Wall wrote:
 To you and me, the fact that there are single quotes means there's
 something there to hide.  But other people think the other way and
 see double quotes as indicating there's something to interpolate.
 I think PBP comes down on that side, but to me, single quotes are a
 little harder to see.  And maybe there's some bias from seeing double
 quotes used non-interpolatively in American English.
 
 FWIW, my reasoning in this area is based on Laziness: single quotes mean I
 don't have to scan the string looking for interpolated stuff when reading
 code.  Double quotes mean I do, and I'm annoyed at the waste of time when I
 scan and find nothing.  Why didn't this guy just use singles here?  It's
 (mildly) misleading.
 
 (There are obviously edge cases, even in Perl 5, but even naive adherence to
 this guideline is a good first approximation, with a second look only
 required in the rarest of cases.)

Normally I'd go on the side of the reader and say yes, when writing code you
should be picky about what quotes you use.  But in this case I find that, on
the writing side, I find it a common annoyance when I chuck a variable into a
string and then only realize afterwards that it's not interpolating.  On the
reading side, I find visually scanning for $ in strings easy and I guess I
assume everyone else does, too.


-- 
We do what we must because we can.
For the good of all of us,
Except the ones who are dead.
-- Jonathan Coulton, Still Alive


Re: Concerns about {...code...}

2007-12-20 Thread Michael G Schwern
Patrick R. Michaud wrote:
 Just to add another perspective, PHP uses curlies inside of
 double-quoted strings to indicate various forms of 
 interpolation, and it doesn't seem to cause major issues
 there.

PHP has 8000 built in functions and it doesn't seem to cause issues there.
I'll not be taking my language design advice from PHP TYVM. ;P


-- 
I am somewhat preoccupied telling the laws of physics to shut up and sit down.
-- Vaarsuvius, Order of the Stick
   http://www.giantitp.com/comics/oots0107.html


Re: Concerns about {...code...}

2007-12-20 Thread Michael G Schwern
Jonathan Scott Duff wrote:
 On Thu, Dec 20, 2007 at 07:58:51AM -0500, Mark J. Reed wrote:
 I think the issue is that bare vars don't interpolate anymore, but
 they still have sigils of their own, so adding to the default interp
 syntax is too noisy:  ${$var} is not really much improvement over
 ${\(expr)}.
 
 That's not quite accurate.  Scalars interpolate as they always have, but
 aggregates need to be followed their respective bracketing construct
 (e.g., My array contains these items: @array[])
 
 The only issues that I see from the original email are:
 1. interpolating scalars but not code
 2. having to be more careful about what type of string you're using
 
 Adriano answered #1 I think:  $yaml = Q:!c{ $key: 42 };
 
 For the second one, if you're really just worried about how prevalent {}
 appear in double-quotish strings, perhaps @Larry could be persuaded to
 make them non-interpolative by default. (i.e., the adverb would be
 required to make them interpolate)

That pretty much sums up my concern.

The gyrations to turn off interpolating code... it's nice to know that exists
but not something I want to ever have to remember or type or even consider my
quoting context.  Interpolate vs not interpolate is enough, I have more
important things to worry about while coding. [1]

Non-interpolative by default... well I don't exactly want the feature to go
away either. [2]  I can see its uses [3] and it potentially eliminates some
otherwise convoluted bits of code.  And again, I don't want to be thinking
about flipping interpolation features on and off for each string.  Even qs//
is more than I want to consider. [4]

Code execution in a string is a very powerful thing, so it's not the sort of
thing one wants to accidentally trigger.  Because it's using a common,
innocent construct, this strikes me as being all too easy to trigger
accidentally and unknowingly.

$ pugs -wle 'sub key() { 42 } sub value() { 23 }  say { key: value }'
23

Whoops.

It's also worth noting that ${} and @{} adding more context flexibility.  It
appears {} only happens in list context right now, though I admit I'm not up
on all the new contexts.


[1] Note, I'm the sort of person that uses  until I have a reason otherwise.

[2] Now being able to turn it ON in a single quoted string would be handy, but
that's just because of my special case writing a lot of make generating
code where $ already has meaning.

[3] Although a lot of them are handled by the interpolation of $obj.method()
which makes me happy.

[4] Which doesn't appear to be documented in S2.


-- 
Look at me talking when there's science to do.
When I look out there it makes me glad I'm not you.
I've experiments to be run.
There is research to be done
On the people who are still alive.
-- Jonathan Coulton, Still Alive


Concerns about {...code...}

2007-12-19 Thread Michael G Schwern
I was reading an article about Perl 6, I forget which one, and it happened to
mention that code can be interpolated inside double quoted strings.  That's
one thing, my concern is with the selected syntax.

say foo { 1+1 };   # foo 2

The {...} construct seems far too common one in normal text to be given
special meaning.  One data point is to do a google code search for { in Perl
5.  It comes up with quite a lot.
http://www.google.com/codesearch?hl=enlr=q=%5C%22%5C%7B+lang%3AperlbtnG=Search

Another concern is embedded YAML.

$yaml = { $key: 42 };   # syntax error in Perl 6

Finally, it chokes on unbalanced braces adding another trap for users.

I'm concerned this will lead to a lot of unsightly backwhacking or having to
be more careful about what type of string you're using.

What about ${} and @{} instead?  ${} would execute in scalar context and @{}
in list.  They're just cleaned up versions of the successful, but ugly, Perl 5
idioms ${\(...)} and @{[...]} idioms.  They make use of an existing
interpolated character so there's no additional load on the programmer.

${} and @{} already have interpolated meanings in Perl 5 but not in Perl 6.


-- 
...they shared one last kiss that left a bitter yet sweet taste in her
mouth--kind of like throwing up after eating a junior mint.
-- Dishonorable Mention, 2005 Bulwer-Lytton Fiction Contest
   by Tami Farmer



Re: no 6;

2005-09-11 Thread Michael G Schwern
On Mon, Sep 05, 2005 at 08:29:00PM +0100, Nicholas Clark wrote:
 It's not valid perl 4:
 
 $ perl4 -e 'no 5; print [EMAIL PROTECTED]' 
 syntax error in file /tmp/perl-em47tij at line 1, next 2 tokens no 5
 Execution of /tmp/perl-em47tij aborted due to compilation errors.

$ perl1 -e 'no 4;  print Happy New Year, 1988!\n'
syntax error in file /tmp/perl-eE52cHQ at line 1, next token string
Execution aborted due to compilation errors.


-- 
Michael G Schwern [EMAIL PROTECTED] http://www.pobox.com/~schwern
Insulting our readers is part of our business model.
http://somethingpositive.net/sp07122005.shtml


Re: Unify cwd() [was: Re: $*CWD instead of chdir() and cwd()]

2005-04-16 Thread Michael G Schwern
On Fri, Apr 15, 2005 at 09:32:23PM -0400, Chip Salzenberg wrote:
  Perl 6 is going to have to decide on some sort of standard internal getcwd 
  technique, $CWD or not.
 
 I don't think Perl 6 has to do anything of the kind.  It would
 be a mistake to try.

Sorry, I had assumed that having a simple cwd() was a forgone conclusion 
so I just tried to bull through it.  My bad.  Lemme back up a few steps and 
try again. [1]

Yes, there are lots of ways to check the cwd each filling in one edge
case or another.  However I'd like to believe its possible to come up with
one simple, safe cwd() that works for 99.9% of the cases and call that cwd().
Then have a Cwd module full of all the various other techniques (or perhaps
attributes to alter the behavior of cwd()).  This lets you answer the 
question How do I get the current working directory? with Short answer: 
cwd().  Long answer: For this set of conditions, use this... 
This avoids the current state of things where a user with a simple
desire must slog through the rather daunting choices provided by Cwd.pm
and probably wind up making the wrong decision. [2]  A high level language
really should smooth all that over.

How cwd() is implemented is not so important as what happens when it hits
an edge case.  So maybe we can try to come up with a best fit cwd().  I'd 
start by listing out the edge cases and what the possible behaviors are.  
Maybe we can choose a set of behaviors which is most sensible across all 
scenarios and define cwd() to act that way.  Or maybe even just define what 
various cwd variations currently do.

Here's the ones I know of off the top of my head.  You probably know more.

* The cwd is deleted
* A parent directory is renamed
* A parent directory is a symlink


[1]  http://angryflower.com/pathof.gif
[2]  The state of Cwd.pm's docs add to my anxiety.



$*CWD instead of chdir() and cwd()

2005-04-15 Thread Michael G Schwern
I was doing some work on Parrot::Test today and was replacing this code
with something more cross platform.

# Run the command in a different directory
my $command = 'some command';
$command= cd $dir  $command if $dir;
system($command);

I replaced it with this.

my $orig_dir = cwd;
chdir $dir if $dir;
system $command;
chdir $orig_dir;

Go into some new directory temporarily, run something, go back to the
original.

Hmm.  Set a global to a new value temporarily and then return to the
original value.  Sounds a lot like local.  So why not use it?

{
local chdir $dir if $dir;
system $command;
}

But localizing a function call makes no sense, especially if it has side
effects.  Well, the current working directory is just a filepath.  Scalar
data.  Why have a function to change a scalar?  Just change it directly.
Now local() makes perfect sense.

{
local $CWD = $dir if $dir;
system $command;
}

And this is exactly what File::chdir does.  $CWD is a tied scalar.
Changing it changes the current working directory.  Reading it tells you
what the current working directory is.  Localizing it allows you to
safely change the cwd temporarily, for example within the scope of a
subroutine.  It eliminates both chdir() and cwd().

Error handling is simple, a failed chdir returns undef and sets errno.

$CWD = $dir err die Can't chdir to $dir: $!;

I encourage Perl 6 to adapt $*CWD similar to File::chdir and simply eliminate
chdir() and cwd().  They're just an unlocalizable store and fetch for global
data.

As a matter of fact, Autrijus is walking me through implementing it in Pugs
right now.



Re: $*CWD instead of chdir() and cwd()

2005-04-15 Thread Michael G Schwern
Thus spake Larry Wall:
 Offhand, I guess my main semantic problem with it is that if a chdir
 fails, you aren't in an undefined location, which the new value of $CWD
 would seem to indicate.  You're just where you were.  Then the user
 either has to remember that, or there still has to be some other
 means of finding out the real location.

To be clear:  Only the store operation will return undef on failure.  
Additional fetches on $CWD will continue to return the cwd.

$CWD = '/path/which/exists';
$CWD = '/i/do/not/exist' err warn $!;
print $CWD;

This prints /path/which/exists/.


 The other problem with it is the fact that people will assign relative
 paths to it and expect to get the relative path back out instead
 of the absolute path.

I honestly never had this problem until I sat down and thought about it. :)
THEN I got all confused and started to do things like $CWD .= '/subdir';
instead of simply $CWD = 'subdir';.  But the rule is simple and natural.
It takes a relative or absolute directory and ALWAYS returns an absolute 
path.  Lax in what inputs it accepts, strict in what it emits.  This is no
more to remember than what chdir() and cwd() would do.

The result from $CWD would simply be a Dir object similar to Ken Williams' 
Path::Class or Ruby's Dir object.  One of the methods would be .relative.

I didn't bring up @CWD because I thought it would be too much in one sitting.
Basically it allows you to do this:

pop @CWD;   # chdir ('..');
push @CWD, 'dir';   # chdir ('dir');
print $CWD[0];  # (File::Spec-splitdir(abs_path()))[0];
# ie. What top level directory am I in?

and all sorts of other operations that would normally involve a lot of
splitdir'ing.

And then there's %CWD which I'm toying with being a per-volume chdir like
you can do on Windows but that may be too much of a questionable thing.


 Your assumption there is a bit inaccurate--in P6 you are allowed to
 temporize (localize) the effects of functions and methods that are
 prepared to deal with it.  

Yeah, we were talking about it on #perl6 a bit.  That seems to me the more
bizarre idea than assigning to something which can fail.  Localizing an
assignment is easy, there's just one thing to revert.  But function calls can
do lots of things.  Just how much does it reverse?  I guess if its used
sensibly on sharp functions, such as chdir, and the behavior is 
user-definable it can work but I don't know if the behavior will ever
be obvious for anything beyond the trivial.

FWIW my prompting to write File::chdir was a desire was for local chdir.
So if temp chdir can be made to work that would solve most of the problem.

If nothing else perhaps chdir() should be eliminated and cwd() simply takes
an argument to make it a getter/setter.


 However, I agree that it's nice to have an
 easily interpolatable value.  So I think I'd rather see $CWD always
 return the current absolute path even after failure

The problem there is it leaves $CWD without an error mechanism and thus
becomes an unverifiable operation.  You have to use chdir() if you want to
error check and $CWD is reduced to a scripting feature.

It could throw an exception but then you have to wrap everything in a try
block.  Unless Perl 6 is going this route for I/O errors in general I'd
rather not.

I'll give the error mechanism some more thought.


Anyhow, I encourage folks to play with File::chdir and see what they think
of the idea.  I'm fixing up the Windows nits in the tests now.



Re: $*CWD instead of chdir() and cwd()

2005-04-15 Thread Michael G Schwern
On Fri, Apr 15, 2005 at 11:52:38PM +0200, Juerd wrote:
  becomes an unverifiable operation.  You have to use chdir() if you want to
  error check and $CWD is reduced to a scripting feature.
 
 Well, after failure it can be cwd() but false without breaking any real
 code, because normally, you'd never if (cwd) { ... }, simply because
 there's ALWAYS a cwd. If this is done, the thing returned by the STORE
 can still be an lvalue and thus be properly reffed.

Good idea!



Unify cwd() [was: Re: $*CWD instead of chdir() and cwd()]

2005-04-15 Thread Michael G Schwern
On Fri, Apr 15, 2005 at 08:31:57PM -0400, Chip Salzenberg wrote:
 According to Michael G Schwern:
  And this is exactly what File::chdir does.  $CWD is a tied scalar.
 
 I don't think current directory maps well on a variable.  That won't
 stop people from using it, of course.  :-(
 
 There are several methods to determine the current directory.  Each
 one has its corner cases, strengths and weaknesses (thus the
 proliferation of Cwd module functions), and it doesn't make any sense
 to me to elevate one over the rest through the proposed $CWD.

This is orthoginal to $CWD.  

Perl 6 is going to have to decide on some sort of standard internal getcwd 
technique, $CWD or not.  In the same way that we have open() not fopen, 
fdopen, freopen... we can choose the safest and most sensible technique for 
determining the cwd and use that.  You have to because when a new user asks 
how do I get the current working directory? you want to say cwd() and 
not Well, there are a variety of different techniques...  Cwd.pm is a 
perfect example of this problem.  Which one should a user use?  Most folks 
just won't care and the micro-differences between the functions in Cwd.pm
aren't worth the trouble.  

Present a sensible default.  Write a module with all the other options for 
those who need it.


   mkdir '/tmp/foo';
   $CWD = '/tmp/foo';
   rename '../foo', '../bar';
   say $CWD;  # Well?  Which is it?

Its exactly the same as...

mkdir '/tmp/foo';
chdir '/tmp/foo';
rename '../foo', '../bar';
say cwd();



Re: .method == $self.method or $_.method?

2005-03-18 Thread Michael G Schwern
On Thu, Mar 17, 2005 at 11:46:52PM +0200, Yuval Kogman wrote:
 I think this should mean $_, and if the user really really really
 wants to do .foo on the invocant, then why not just say:
 
 method bar ($_:) { 
   .foo;
 }

Because $_ can change.

method bar ($_:) {
.foo;
map { .baz } 1..10;  # whoops
}


 This keeps $_ unambiguosly the 'it', while 'this' is more specific.

I'm not proposing changing what $_ means, I'm proposing changing what .method 
means.  Instead of $_.method make it mean $invocant.method.  Sooo I'm not
really sure where all that extra stuff about $_ was going, true as it may be.


 Perhaps i'm sort of forcing this distinction.
 
 However, I wouldn't be too happy with having to do this, though:
 
   method data {
   map { $OUTER::_.process($_) } .things;
   }
 
 or having to name the invocant every time I want to map {}.

Right.  I believe the times one will want to do a method call on $_ when it
is *not* the invocant will be greatly outnumbered by the times when you
want to do a method call on the invocant.  Thus adding ambiguity to .method
is not worth it.


 Lastly, what is wrong with
 
   $.method?

As I understand it, $invocant.method and $.method are different.  The first
is a public attribute the second is a method call, no?  And while all
attributes have an associated method (as I understand, ie. foreach $.foo, 
$invocant.foo should always be the same) the reverse is not true.
Foreach $invocant.foo there need not be a $.foo.

If this assumption is incorrect then my argument does collapse.



Re: .method == $self.method or $_.method?

2005-03-18 Thread Michael G Schwern
This drifed off list but I don't think that was intentional.

- Forwarded message from Yuval Kogman [EMAIL PROTECTED] -

From: Yuval Kogman [EMAIL PROTECTED]
Date: Fri, 18 Mar 2005 01:12:42 +0200
To: Michael G Schwern [EMAIL PROTECTED]
Subject: Re: .method == $self.method or $_.method?
User-Agent: Mutt/1.5.6i

On Thu, Mar 17, 2005 at 14:42:06 -0800, Michael G Schwern wrote:
 Because $_ can change.
 
   method bar ($_:) {
   .foo;
   map { .baz } 1..10;  # whoops
   }

I don't see it as a whoops. It's either or, and the user gets to
choose.

I read that as:

method bar ($self:) { for ($self) {
...
}}

BTW, given:

method bar {
# what's $self named in here?
# do you need to name it for it to be accessible?
}

S12 does not specify, as far as I can tell.

Perhaps the desired behavior could be: If the invocant is not
specified it is the default, i.e

method bar {

}

is really

method bar ($_:) {

}

and the user assumes responsibility for not resetting $_ if they
would like to keep it.

 As I understand it, $invocant.method and $.method are different.  The first
 is a public attribute the second is a method call, no?  And while all
 attributes have an associated method (as I understand, ie. foreach $.foo, 
 $invocant.foo should always be the same) the reverse is not true.
 Foreach $invocant.foo there need not be a $.foo.

I think you are right... But here is an idea:

The only conflict I see with the reverse not being true is if you
would like to avoid calling the is rw accessor when you want to set
the attribute from within the class.

This assumes that $.attribute = ... from within an accessor means
the attribute itself, as a special case, and that all accessors are
rw when their caller is eq ::?CLASS.

Again, the problem is that an accessor that is rw and does funny
stuff to it's attribute could not be avoided when a sibling method
wants to just fudge the attribute.

On second thought, this problem seems bigger now. Opinions?

-- 
 ()  Yuval Kogman [EMAIL PROTECTED] 0xEBD27418  perl hacker 
 /\  kung foo master: /me beats up some cheese: neeyah!




- End forwarded message -

-- 


Re: .method == $self.method or $_.method?

2005-03-18 Thread Michael G Schwern
[ Sorry if my replies to this thread have seemed a little disjoint.  I just
  realized I'd unsubscribed myself from p6l last year when I started a $job$
  and never resubscribed.  So I'd only been seeing fragments of the 
  conversation.  Catching up from the archives...
]

Larry's idea of making $_ == $self in methods seems to swing the
pendulum the other way.  Now its a shame to have to make everything
explicit inside map, grep, and short for loops etc...  And yes, what about
given?

My immediate reaction to o.method and c.method was a little bit of the
heebie-jeebies but then I remembered hey, I wrote CLASS.pm so I could do
CLASS-method and its exactly the same thing, a constant function which
returns the name of the class.  Then c.method doesn't seem so weird.

And if you want to be crazy I suppose you can define your own c() and o()
functions. :)

Its shorter than $self.method and it solves the $_ ambiguity problem so that's
good.  Its a shame to lose the even shorter .method for an extremely common
task but I'm not going to quibble to much over a single character.

What it doesn't solve is the $.method vs .method issue.  They look similar
but one works on the invocant and one works on $_.  Still a trap.



.method == $self.method or $_.method?

2005-03-17 Thread Michael G Schwern
There's a discussion going on #perl6/irc.freenode.org right now wondering
about what .method means.  We'd all assumed it meant $self.method (where
$self is always the method invocant) but then had a look at Synopsis 12 
which states 

  Dot notation can omit the invocant if it's in $_:

.doit(1,2,3)

This seems to cripple .method's usefulness by coupling it to $_ which
can change often.  Now in order to be safe for anything but trivial methods 
you're back to writing out $self all over the place, something that Perl 6 
was supposed to fix about Perl 5.

It has also been pointed out that .foo, $.foo, @.foo and %.foo are all
(intentionally) similar and all but one operates on the invocant.  Only
.foo operates on $_.  This seems like a newbie trap waiting to happen.
MOST of the time .foo will work like $self.foo but every once in a while
they'll get caught in a gotcha.

Thoughts?


Re: .method == $self.method or $_.method?

2005-03-17 Thread Michael G Schwern
On Thu, Mar 17, 2005 at 06:04:56PM +1100, Adam Kennedy wrote:
 I should add that Darren and I, who both have similar tendencies towards 
 larger scale coding where consistency is far preferred to compactness, 
 both ended up concluding that our style policies will be to _always_ use 
 explicit invocants (except of course for one liners).

I thought your conclusion was you'd only use an explicit invocant if .foo
meant $_.foo.  And to drop it if .foo means $self.foo as there's no 
ambiguity.



Re: .method == $self.method or $_.method?

2005-03-17 Thread Michael G Schwern
On Thu, Mar 17, 2005 at 07:00:08PM +1100, Adam Kennedy wrote:
 The only minor thing I 
 can see would be that you will end up with a slight asymmetry question 
 of if we use $:attribute for a private attribute, do we call :method 
 for a private method?

That occurs no matter if .method means $self.method or $_.method.

Anyhow, I don't see why not. :)



Re: OO inheritance in a hacker style

2004-01-28 Thread Michael G Schwern
On Wed, Jan 28, 2004 at 03:18:24PM +0300, Dmitry Dorofeev wrote:
 I am not very good at OO but I tried at least 2 times to develop with it 
 though :-)
 Last time it was Java. The problem is that when i going to use some 
 'standard' class
 or 3d party class i'd rather to cut off all unnecessary methods (and may be 
 even properies!),
 then adding my own. I know it kills inheritance but it is much more to my 
 Perl habit of hacking code.

There's little benefit to explicitly stubbing out inherited methods you 
don't plan to use, just don't use them.  Its not worth screwing up
the language's inheritence model with an explicit way to have a subclass 
not implement its parent's interface.

I suspect that if you find yourself only needing a small fraction of your
parent's interface often, inheritence might not be the right thing.  Consider
delegation instead.


-- 
Michael G Schwern[EMAIL PROTECTED]  http://www.pobox.com/~schwern/
You're more radiant than a memory of breathtaking ecstasy.


Re: 'Core' Language Philosophy [was: Re: 'catch' statement modifier]

2003-11-27 Thread Michael G Schwern
On Wed, Nov 26, 2003 at 03:56:28PM -0500, Mark J. Reed wrote:
 Nicer it may be, But I use File::Find *because* it's in the core,
 so I don't have to worry about my programs being non-portable because I
 use a module that may not be installed.  

Of course with Perl 6 modules will be MUCH easier to install. :)


-- 
Michael G Schwern[EMAIL PROTECTED]  http://www.pobox.com/~schwern/
Cottleston, Cottleston, Cottleston Pie.
A fly can't bird, but a bird can fly.
Ask me a riddle and I reply:
Cottleston, Cottleston, Cottleston Pie.


Re: The C Comma

2003-11-24 Thread Michael G Schwern
On Mon, Nov 24, 2003 at 05:00:38PM -0700, Luke Palmer wrote:
 The C comma has always bugged me, but its function is indeed useful
 (many times I use Cand in its place, if I know the left side will
 always be true). I don't know whether it's staying or not (I've heard
 rumors of both), but I'd suggest that it leave and allow itself to be
 replaced by a word, alongside Cand, Cor, and Cerr.

It certainly would solve the annoying Perl 5 is it a list constructor or
the comma operator?  No more user confusion and simpler parsing.  Maybe
even eliminate some more parens!  @foo = 1,2,3;

That reason alone is enough for me.


 This word:  Cthen.  
 
 So, from a recent script of mine:
 
 my $n;
 while $n++ then @accum  $total {
 ...
 }
 
 (Where I got in trouble for using Cand and never executing anything :-)
 
 To me, it's very clear what's going on, and eliminates the mystery of
 the comma in scalar context for a syntax error.

I definately agree that this is used rarely enough that it should be a word
and not a single character.

then sounds too much like if/then which is confusing.  Its exactly
the opposite from what you're trying to convey.

It also doesn't convey anything about evaluate the left hand side, ignore 
the results and evaluate the right.  Unfortunately, I don't have a better 
name.


-- 
Michael G Schwern[EMAIL PROTECTED]  http://www.pobox.com/~schwern/
Now we come to that part of the email you've all been waiting for--the end.


Re: Apocalypses and Exegesis...

2003-08-14 Thread Michael G Schwern
On Thu, Aug 14, 2003 at 12:52:42PM +0100, Alberto Manuel Brandão Simões wrote:
 Apocalypses and Exegesis are not an 'official' specification for Perl6,
 I mean, they are subject to change. Is there any idea when will we have
 a freeze on the syntax and features for perl6?

Its scheduled to occur shortly following Hell. ;)


-- 
Michael G Schwern[EMAIL PROTECTED]  http://www.pobox.com/~schwern/
WOOHOO!  I'm going to Disneyland!
http://www.goats.com/archive/980805.html


Re: %_ - is it available for use?

2003-08-02 Thread Michael G Schwern
 Damian Conway [EMAIL PROTECTED] writes:
 Hence, making C%_ mean something different in core Perl 5 might possibly be 
 forwards incompatible.

Representing the Backwards Compatiblity Police, I've had co-workers use
%_ as the globalist of all global hashes.  %_ transends all packages and
scopes and Perl does not localize it, touch it or use it as it does @_ and 
$_.  In the particular case I'm thinking of, it was used to hold global
arguments for function calls in a template system.  Rather insane, really.
Lots of better ways to do it and clearly making use of an undefined
language feature.

I'm not making an argument against %_, just noting that *_ is used 
opportunisticly and you will break a few programs.


-- 
It's Crack Cocaine time!


Re: %_ - is it available for use?

2003-08-02 Thread Michael G Schwern
On Sun, Aug 03, 2003 at 01:37:16AM +0200, Abigail wrote:
 I am fond of doing
 
 local %_ = @_;
 
 as one of the first statements of a subroutine. That, or 
 
 my %args = @_;
 
 I like the latter because it uses a lexical variable, but I like the
 former because %_ fits with @_ and $_.

FWIW, local() is quite a bit slower than my().

$ perl5.8.1 local_vs_my 100
  Rate localmy
local 180180/s--  -30%
my257069/s   43%--

$ cat local_vs_my
#!/usr/bin/perl -w

use Benchmark 'cmpthese';

cmpthese( shift || -3, {
local   = sub { local %_ = @_; },
my  = sub { my %args = @_; },
});


-- 
Welcome to the Office Of Naval Contemplation


Re: %_ - is it available for use?

2003-08-02 Thread Michael G Schwern
On Sat, Aug 02, 2003 at 08:16:19PM -0700, Larry Wall wrote:
 On Sat, Aug 02, 2003 at 04:33:19PM -0700, Michael G Schwern wrote:
 : I'm not making an argument against %_, just noting that *_ is used 
 : opportunisticly and you will break a few programs.
 
 Not necessarily.  If Perl 6 were to use %_ as parameter name, it
 would be lexically scoped, and hide any package %_ only in that scope.

Sorry, p5p-cross talk, I was referring only to Perl 5.


-- 
Any sufficiently encapsulated hack is no longer a hack.


Re: How shall threads work in P6?

2003-03-31 Thread Michael G Schwern
On Mon, Mar 31, 2003 at 08:13:09PM +0200, Matthijs van Duin wrote:
 I think we should consider cooperative threading, implemented using 
 continuations.  Yielding to another thread would automatically happen when 
 a thread blocks, or upon explicit request by the programmer.
 
 It has many advantages:

It has major disadvantages:

I must write my code so each operation only takes a small fraction of time
or I must try to predict when an operation will take a long time and yield
periodicly.

Worse, I must trust that everyone else has written their code to the above
spec and has accurately predicted when their code will take a long time.


Cooperative multitasking is essentially syntax sugar for an event loop.  We
already have those (POE, Event, MultiFinder).  They're nice when you don't 
have real, good preemptive threads, but cannot replace them.  It is a great
leap forward to 1987.

The simple reason is that with preemptive threads I don't have to worry 
about how long an operation is going to take and tailor my code to it, 
the interpreter will take care of it for me.  All the other problems with 
preemptive threads aside, that's the killer app.


We need preemptive threads.  We need good support at the very core of the
langauge for preemptive threads.  perl5 has shown what happens when you
bolt them on both internally and externally.  It is not something we can
leave for later.

Cooperative multitasking, if you really want it, can be bolted on later or
provided as an alternative backend to a real threading system.


-- 
I'm spanking my yacht.


Re: Spare brackets :-)

2003-01-29 Thread Michael G Schwern
On Tue, Jan 28, 2003 at 12:11:18PM +1300, [EMAIL PROTECTED] wrote:
 This may sound like a silly idea but ...
 
 Has anyone considered removing with the syntactic distinction between
 numeric and string indexing -- that is, between array and hash lookup?

PHP works this way.
http://www.php.net/manual/en/language.types.array.php

So that makes a nice case study to investigate.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One



Re: Disappearing code

2003-01-10 Thread Michael G Schwern
On Thu, Jan 09, 2003 at 07:55:20PM -0500, John Siracusa wrote:
 Has there been any discussion of how to create code in Perl 6 that's there
 under some conditions, but not there under others?  I'm thinking of the
 spiritual equivalent of #ifdef, only Perlish.
 
 In Perl 5, there were many attempts to use such a feature for debugging and
 assertions.  What everyone wanted to do was write code like this:
 
 debug(Doing foo with $bar and $baz);
 foo($bar, $baz);

I would assume it to be a compiler hint via subroutine attribute.

sub debug ($msg) is off {
print STDERR $msg;
}

some this subroutine is a no-op if a flag is set attribute.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One



Re: Disappearing code

2003-01-10 Thread Michael G Schwern
On Thu, Jan 09, 2003 at 11:15:49PM -0500, John Siracusa wrote:
 On 1/9/03 10:10 PM, Michael G Schwern wrote:
  I would assume it to be a compiler hint via subroutine attribute.
  
sub debug ($msg) is off {
  print STDERR $msg;
}
  
  some this subroutine is a no-op if a flag is set attribute.
 
 Hm, not quite as convenient as setting a package global (constant)
 somewhere.  Maybe that same off bit could be set from a distance at
 compile time?

That would be the if a flag is set part.  Point is, its easily handled
by some sort of subroutine attribute which looks at some flag somewhere.

'off' was a bad name for it.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One



Re: tree frobbing facilities in Perl6?

2002-12-24 Thread Michael G Schwern
 {
push @%procs{$pid}{$key}, $proc{$key};
}
}
}

YAML::Dump(%procs);

This would produce something like:

123:
time: [123456789, 234567890]
pcpu: [4.6, 2.4]
stat: [SN+, R]
234:
time: [123456789]
pcpu: [2.3]
stat: [R]
456:
time: [234567890]
pcpu: [3.4]
stat: [SN]


 is not something I want to try in XSLT.  I can do it in Perl, of course,
 but I end up writing a lot of code.  Am I missing something?  

I think your external format (XML which is a tree) is not mapping well to
your internal format (Perl which uses hashes,arrays and scalars) causing you
to have to shuffle your awkward XML-tree structure into something more
Perlish.  By picking an external format, YAML, which maps better to your
internal format you can avoid the intermediate step.

Alternatively, I'm sure you can rewrite your XML parser to produce a
structure similar to that which YAML produces.  The point being to pull in
your data in a way which better fits Perl.


 And, to bring the posting back on topic, will Perl6 bring anything 
 new to the campfire?

Hyperoperators will help.  A simplified slicing syntax, especially when
dealing with references, will help.  A simplified reference syntax helps,
too.

And, of course, Perl 6 will hopefully ship with a YAML parser. ;)


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
My enormous capacity for love is being WASTED on YOU guys
-- http://www.angryflower.com/497day.gif



Re: tree frobbing facilities in Perl6?

2002-12-24 Thread Michael G Schwern
On Tue, Dec 24, 2002 at 09:51:07AM -0800, Rich Morin wrote:
 So with simple data like this, I'd just use YAML.  This isn't really
 important, just a YAML plug. :)  But it does have a better resulting data
 structure as we'll see below.
 
 I went to a talk on YAML and was quite impressed, overall.  My main issue
 with it is that it isn't buzzword-compliant.  As I'm hoping to have other
 folks write programs to read my files at some point, this may be an issue.

FWIW there's Perl, Ruby and Python implementations.  A C library is in the
works and I think someone's doing a Java one.

And, of course, you can always just...

$ xyx ps.yml  ps.xml
$ cat ps.xml
ps
  processes
statSN+/stat
pcpu4.6/pcpu
pid123/pid
  /processes
  processes
statR/stat
pcpu2.3/pcpu
pid234/pid
  /processes
  time123456789/time
/ps
ps
  processes
statR/stat
pcpu2.4/pcpu
pid123/pid
  /processes
  processes
statSN/stat
pcpu3.4/pcpu
pid456/pid
  /processes
  time234567890/time
/ps

(For this example I put the top level ps: back into the YAML so it would
translate better into XML)

xyx is just a really thin wrapper around YAML.pm and XML::Simple.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
It wasn't false, just differently truthful.
-- Abhijit Menon-Sen in [EMAIL PROTECTED]



Re: Everything is an object.

2002-12-12 Thread Michael G Schwern
On Thu, Dec 12, 2002 at 10:40:20PM -, Smylers wrote:
 What if the thing being Csorted (or whatever) is not an array but a
 list?
 
   @out = sort $scalar, @array, result_of_calling_function($param);
 
 Would the list have to be stored in an array before it could be sorted?

I would hope Perl would be smart enough to allow this:

  @out = ($scalar, @array, result_of_calling_function($param)).sort

which Ruby does:

  $ ruby -wle 'out = [foo, bar].sort;  print out.join  ' 
  bar foo

but as I said, I find the Lisp flow style worth keeping.

  @out = join \n, map {...} grep {...} sort {...} @foo


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Pancakes is the better part of valor.
http://www.goats.com/archive/971202.html



Everything is an object.

2002-12-11 Thread Michael G Schwern
This is just your friendly neighborhood curmudgeon reminding you that in
Perl 6, everything is an object.  This is a concept that, as Perl
programmers, we're not familiar with.

What are the consequences of this in language design?  Well, it means not
every new piece of functionality requires a new operator.  Instead, consider
a method.  Its an actual word.

Stemming the tide of new grammar and operators heads off another
problem, typos becoming meaningful.  The more operators you have, the more
chance that this sort of thing:

   if $num1 === $num2 {
  ...

will be hard to find.  Was it a typo or did they really mean to do a shallow
object comparison?


Instead of introducing new built-in functions they can be done as methods.
This reduces core namespace pollution.  Think of the core like a big CPAN
module.  Every built-in is like an exported function.  Every word used as a
built-in is one that noone else can safely use for something else in their
own code.


If you want a tactile grasp of the Everything is an object concept, try
some Ruby.

Many pieces of edge functionality which are useful but would have been
rejected because they don't really warrent a new built-in or operator can be
put in as methods.  For example, in Ruby you can alter the default value of
a hash like so:

h = {foo = 42};
h.default = wibble;

# Prints 'wibble' rather than undef.
print h[bar];

Isn't that neat?  Not important enough to warrent a new built-in, but
something nice to have in your toolbox.

How many times have you done this in perl:

print grep defined, @array;

in Ruby, its just this:

print array.compact

I find myself doing this alot:

   $string =~ s/^\s+//;
   $string =~ s/\s+$//;

in Ruby:

   string.strip!

Ruby can add neat little features without long deliberations about the
impact on language growth and backwards compatibilty because they have the
ability to add methods to core types.

A flip through the Ruby builtin methods is nice for building up some envy. :)
http://www.rubycentral.com/book/builtins.html


Sometimes you do need to use an operator or built-in.  Usually to make data
transformations flow nicely:

  @foo = join \n, map { ... } grep { ... } sort @bar;

the concept can be reversed:

  @foo = @bar.sort.grep(...).map(...).join(\n);

but is that Perlish?

Or you will commonly use the operator on expressions rather than variables.

   1 + 2 == 3

would suck as:

   (1 + 2).eq 3


There's lots of reasons to use an operator or built-in instead of a method,
but remember to make the consideration first.  Don't go grammar happy.


In closing:  Consider a method rather than a built-in or operator.
Everything is an object.  Tattoo it on your forehead today.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Do you actually think about what you are saying or is it an improvisational 
game of Mad Libs that you play in your head?




Re: Everything is an object.

2002-12-11 Thread Michael G Schwern
On Wed, Dec 11, 2002 at 04:56:03PM -0800, Michael Lazzaro wrote:
 First, universal operators and universal methods both pollute the 
 useful (programmer) namespace to nearly the same extent.

Most of the methods are not universal.  For example:

 $foo.compress

would be in the String class, not Object (or whatever we're calling the
equivalent of UNIVERSAL today), and only inherited by those objects which
wish to masquerade as strings.

 %hash.default

is in the Hash class.

The sameas example:

 $obj.sameas $obj2

would be in the Object class and would pollute.  Using Ruby as a rough
guide, there aren't many of those.
http://www.rubycentral.com/book/ref_c_object.html


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
One disease, long life.  No disease, short life.



Re: Partially Memoized Functions

2002-12-10 Thread Michael G Schwern
On Tue, Dec 10, 2002 at 10:46:07PM -, Smylers wrote:
  The example above is a classic example of premature optimization.
  There's nothing which ways the cache would be counter-productive for
  simple calculations since the caching logic is nearly as simple.
 
 OK.  There was something on MJD's QOTW recently where using the current
 Perl 5 Memoize module slowed code down -- that gave me the impression
 that caching had the potential.

Applying memoization to really simple calcuations, such as the number of
days in a month, will probably wind up slower than just doing the original
calcuation.  This is also an example of premature optimization. :)

For something as simple as your example, the cost of entering and exiting
the subroutine is probably more expensive than the code to actually do the
work.  In that case you likely want to inline the code which flies off into
a whole other class of optimizations...


  However, if you *really* want to do partial caching and given that
  this is an edge case, ...
 
 It wasn't supposed to be claiming to be a serious function where caching
 would be useful!

I meant that the idea of partial caching is an edge case.


  I'd say to just do it as two functions
 
 Yeah, I thought of that (thanks for bothering to write it out) then I
 thought of having the caching be per-Creturn and couldn't work out
 whether it'd be generally useful or not, which is why I asked here, for
 an increased sample size.
 
 And that increased sample size indicates not, so I'll forget about it.

I dunno, my motto is never hurts to put it in a library.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
MERV GRIFFIN!



Re: Partially Memoized Functions

2002-12-09 Thread Michael G Schwern
On Mon, Dec 09, 2002 at 08:36:20PM -, Smylers wrote:
 Last month's discussion on memoization[*0] had the consensus that
 Ccached is the appropriate property name, used like so:
 
   sub square (Num $n) is cached { ... }
 
 I was wondering whether it'd be better to have this specified per
 Creturn rather than per Csub.  That'd permit something a long the
 lines of:
 
   sub days_in_month(Str $month, Int $year)
   {
 $month = lc $month;
 if $month eq 'feb'
 {
   # Do 'complicated' calculation and cache the result for later use:
   my $leap = $year % 4 == 0
($year % 100 != 0 || $year % 400 == 0);
   cache_and_return $leap ? 29 : 28;
 }
 
 else
 {
   # Simple look-up, so caching would be counter-productive:
   return %days{$month};  # %days was declared above (honest)
 }
   }
 
 That way a function could decide to cache some return values but not all
 of them.

The example above is a classic example of premature optimization.  There's
nothing which ways the cache would be counter-productive for simple
calculations since the caching logic is nearly as simple.

However, if you *really* want to do partial caching and given that this is
an edge case, I'd say to just do it as two functions rather than making the
caching semantics more involved.

   my %days = (...);
   sub days_in_month(Str $month, Int $year)
   {
 $month = lc $month;
 return days_in_feb($year) if $month eq 'feb';
 return %days{$month};
   }

   sub days_in_feb(Int $year) is cached
   {
 # Do 'complicated' calculation and cache the result for later use:
 my $leap = $year % 4 == 0
  ($year % 100 != 0 || $year % 400 == 0);
 return $leap ? 29 : 28;
   }

Of course there's nothing which says you can't just do *both*.
cache_and_return() is merely a function.  Write it, stick it in a library,
distribute for fun and/or profit.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
If God made anything more guerrila than your breast, I hope he kept it for
your father.



seperate() and/or Array.cull

2002-12-04 Thread Michael G Schwern
(The post about 'purge' just made me remember this idea)

Lets say you have a list of program arguments.

@ARGV = ('foo', '--bar=baz', 'yar');

and you want to seperate that into two lists.  One of switches and one of
normal args.  You can't just use a grep, you'd have to do this:

my @switches = ();
my @args = ();
foreach (@ARGV) {
if( /^-/ ) {
push @switches, $_;
}
else {
push @args, $_;
}
}

and that's just entirely too much work.  I'd love to be able to do it with a
grep like thing.

 (@switches, @args) = seperate /^-/, @ARGV;

seperate() simply returns two lists.  One of elements which match, one of
elements which don't.  I think Perl 6 will allow the above syntax to work
rather than having to play with array refs.


An alternative/additional way to do it would be as an Array method.

   @switches = @ARGV.cull /^-/;

Array.cull would remove and return a list of every element in @ARGV which
matched.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Let me check my notes.
http://www.sluggy.com



Re: seperate() and/or Array.cull

2002-12-04 Thread Michael G Schwern
On Wed, Dec 04, 2002 at 08:08:48PM -0700, Luke Palmer wrote:
 About your idea, though, I'm rather indifferent.  However, a friend of
 mine once asked me if Perl had search or find operation, returning
 the Iindex of matching elements.  Now am I just being braindead, or
 is Perl actually missing this operation?  Do you really have to:
 
 my $index;
 for @a {
 last if la_dee_daa;
 $index++;
 }
 
 That can't be right

You can do it with a map without much trouble:

my @indexes = map { /condition/ ? $i++ : () } @stuff;

Its so rare that you work by array index in Perl.  Usually things flow
together element by element.  Sort of like how you rarely handle strings
character by character which can severely confuse C programmers.

What was your friend trying to do?


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Stupid am I?  Stupid like a fox!



Re: String concatentation operator

2002-11-14 Thread Michael G Schwern
On Thu, Nov 14, 2002 at 12:19:47PM +, Andy Wardley wrote:
 Can we overload + in Perl 6 to work as both numeric addition
 and string concatenation, depending on the type of the operand 
 on the left?

 I realise the answer is probably not, given the number/string
 ambiguity of Perl variables:
 
   my $a = 123;
   my $b = 456;
   $a + $b; # 579 or 123456?

Its worse than that, what does this do:

 sub add ($num1, $num2) {
 return $num1 + $num2;
 }

 add($foo, $bar);

There are obvious simple cases

  $foo = 23; $bar = 42; (perl can figure this one out easy)
  $foo = foo;  $bar = bar;  (perl can figure ditto)

but it rapidly gets ambiguous

  $foo = 23; $bar = 'bar';
  $foo = '23';   $bar = 42;

so maybe you can solve it with types:

  sub add (number $num1, number $num2) {
  ...
  }

but what about this very simple case:

  # We read in from a file, so should Perl consider them 
  # strings or numbers?
  @numbers = slurp 'number_file';  chomp @numbers;
  $total = $numbers[0] + $numbers[1];

then you have to do something like this:

  number @numbers = slurp 'number_file';  chomp @numbers;
  $total = $numbers[0] + $numbers[1];

and I really, really, really don't want to even have to think about types
for basic tasks.

No matter what you decide 23 + 'bar' should do (should it concat? should it
add? should it be an error?) it will be wrong to 2/3 of the population
because the add/concat idea violates the cardinal rule of overloading:

Don't make the same op do two different things.

While people might think string concatination is the same as numeric
addition, its really quite a different operation.  If we were to try and
make + do similar things for both it would either be:

 23  + 42  == 64;
 'a' + 'c' == 'd';

or

 'a' + 'c' == 'ac';
 23  + 42  == 2342;

If you find yourself having to decide between two radically different
behaviors when a binary op is presented with two different types, something
is wrong.

The real question is: should adding two strings to anything at all?

And the real question below that one is: how far should type coercion go?

In Perl 5 it stops at a sane point:

  $ perl -wle 'print bar + foo'
  Argument foo isn't numeric in addition (+) at -e line 1.
  Argument bar isn't numeric in addition (+) at -e line 1.
  0

Ok, so string + string does something almost as odd as C does, but at least
it warns about it.  And that's probably a good default way to handle it.

copout type=standardAnd you can always just change the behavior of
strings in a module./copout


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Monkey tennis



Re: String concatentation operator

2002-11-14 Thread Michael G Schwern
On Thu, Nov 14, 2002 at 09:10:07PM +, Richard Proctor wrote:
 There have been times when I have wondered if string concatination could be
 done without any operator at all.  Simply the placement of two things
 next to each other as in $foo $bar or $foo$bar would silently concatenate
 them.  But then I feel there are some deep horrors and ambiguities that
 I have failed to spot...

Before this starts up again, I hereby sentence all potential repliers to
first read:

string concatenation operator - please stop
http://archive.develooper.com/perl6-language;perl.org/msg06710.html


and then read *all* the old proposals and arguments about why they won't
work:

s/./~/g
http://archive.develooper.com/perl6-language;perl.org/msg06512.html

Sane + string concat prposal
http://archive.develooper.com/perl6-language;perl.org/msg06578.html

YA string concat propsal
http://archive.develooper.com/perl6-language;perl.org/msg06598.html

Dot can DWIM without whitespace
http://archive.develooper.com/perl6-language;perl.org/msg06627.html

Another string concat proposal
http://archive.develooper.com/perl6-language;perl.org/msg06639.html

YAYAYA string concat proposal
http://archive.develooper.com/perl6-language;perl.org/msg06650.html

a modest proposal Re: s/./~/g
http://archive.develooper.com/perl6-language;perl.org/msg06672.html



-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Here's hoping you don't become a robot!



Re: Indeterminate math

2002-10-18 Thread Michael G Schwern
On Tue, Oct 15, 2002 at 04:07:51PM -0700, [EMAIL PROTECTED] wrote:
 [1]: This comes from a recent discussion on perlmonks where i attempted
 to formally iron things out for people, since i have yet to see anywhere
 thus far on the web where it was actually formalized.
 (formalization being markedly different from rationalization)
 http://www.perlmonks.org/index.pl?node_id=203698

Here's two simple proofs by contradiction.

Let  1/0 == +Infinity
Then 1 == +Infinity * 0
Since anything times 0 == 0
 1 == 0
Contradiction.

Here's another way to look at it.

0 * 1/0 == ?
On the one hand, anything times 0 == 0.  So it's 0.
On the other hand, a * b/a == b. So it's 1.
Contradiction.

I don't know exactly what you're looking for in terms of formal proofs,
but the above math will hold just fine.


For more a more complete analysis of what happens when you try to
introduce infinity into the real number system, see:
http://mathforum.org/library/drmath/view/55764.html

-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
This is my sig file.  Is it not nify?  Worship the sig file.
http://www.sluggy.com



Re: Indeterminate math

2002-10-15 Thread Michael G Schwern

On Tue, Oct 15, 2002 at 01:44:50PM -0500, Jonathan Scott Duff wrote:
 People have used the terms error and exception interchangably in
 this disucssion.  To me, an error is something that stops program
 execution while an exception may or may not stop execution depending
 on what the user decides to do about exceptions.

Unless I've missed my mark, Perl errors have always been trappable [1].  Does
that make them exceptions?  We've been calling them errors for years now.

Put another way, is there a significant difference between:

eval {
$foo = 1/0;
print Bar;
}
if( $@ =~ /^Illegal division by zero/ ) {
... oops ...
}

and

try {
$foo = 1/0;
print Bar;
}
catch {
when /^Illegal division by zero/ {
... oops ...
}
}

(putting aside that exception handlers stack).

Whatever you call it, exception or error, it will halt the program if left
unhandled.


[1] Less the few odd really hard core the interpreter is having a bad trip
sort of errors.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Here's hoping you don't harbor a death wish!



Indeterminate math

2002-10-14 Thread Michael G Schwern

This came up at YAPC::Europe.  Someone [1] wanted to know if 1/0 would
produce a divide by zero error in Perl 6, or if it would return a value
representing an indeterminate result (undef?)  It would make more sense for
Perl, upon being given a simple bit of impossible math, to return undef
(like other functions do on failure) than to generate an error.  The error
seems a throwback to earlier days of hardwired calculators.

If nothing else it would make guarding against indeterminate math easier.
Rather than the user having to trap an error, or do possibly complicated
work to see if any of the denominators might be zero, you can just see if
the result is undef.


[1] I apologize for forgetting who.

[2] Discussion of divide by zero and why it's not infinity [3]
http://mathforum.org/dr.math/faq/faq.divideby0.html

[3] I was always taught it's infinity.

-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Don't worry, baby, my wrath can be pretty groovy.
http://www.goats.com/archive/980804.html



Re: untaintby property

2002-10-14 Thread Michael G Schwern

On Mon, Oct 14, 2002 at 10:09:41AM -0400, [EMAIL PROTECTED] wrote:
 SUMMARY
 
 The 'untaintby' property restricts which modules may untaint the data or
 data derived from that data.

 DETAILS
 
 I was recently using a module I downloaded from CPAN and looking through
 the code I discovered that it untainted certain data that it had no
 business untainting (IMHO).  The untainting was an unintended byproduct of
 some otherwise useful work. (See my earlier concern about untainting at
 http://makeashorterlink.com/?Y28261A12)

The concern here seems to be more about unintentional untainting rather than
deliberate untainting by unauthorized parties.  Rather than add an
additional, explicit security system on top of an implicit security system,
the causes of unintentional untainting in the language should be reduced.

Something in the family of your original /T regex proposal would make more
sense.  Attack the problem at its source.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Do you have a map? Because I keep getting lost in your armpits.



Re: Indeterminate math

2002-10-14 Thread Michael G Schwern

On Mon, Oct 14, 2002 at 05:45:23PM -0400, [EMAIL PROTECTED] wrote:
 The problem with returning undef is that undef numifies to zero.

Yes, but it does produce a warning.

 It would make more sense if either 1/0 returned NaN, if Perl6 has NaN, or 
 throw an error, which Larry has indicated will be a concept in Perl6.

What happens when NaN is used in an expression?  Is NaN + 0 == NaN?


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
11. Every old idea will be proposed again with a different name and
a different presentation, regardless of whether it works.
 -- RFC 1925



Re: Indeterminate math

2002-10-14 Thread Michael G Schwern

On Mon, Oct 14, 2002 at 07:48:23PM -0400, Mark J. Reed wrote:
 Actually, 1/0 is not NaN; it's +Infinity.  You only get NaN out of
 dividing by 0 if the numerator is either infinite or also 0.

There are several verbal proofs why 1/0 is not +Infinity here:
http://mathforum.org/dr.math/faq/faq.divideby0.html 


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Plus I remember being impressed with Ada because you could write an
infinite loop without a faked up condition.  The idea being that in Ada
the typical infinite loop would be normally be terminated by detonation.
-- Larry Wall in [EMAIL PROTECTED]



Re: Indeterminate math

2002-10-14 Thread Michael G Schwern

On Mon, Oct 14, 2002 at 08:25:43PM -0400, Mark J. Reed wrote:
 On 2002-10-14 at 20:15:33, Michael G Schwern wrote:
  There are several verbal proofs why 1/0 is not +Infinity here:
  http://mathforum.org/dr.math/faq/faq.divideby0.html 

 Yeah, that would be why I sent my followup.   I did not mean to
 imply that 1/0 is positive infinity in real world math.

Sorry, I was a little too fast on the reply gun.


 However, returning Infinity when asked to divide a finite 
 number by 0 is conformant behavior according to the IEEE spec.
 An implementation is *allowed* to indicate an error on division
 by 0, but is not *required* to - returning infinity is legal.

snip

 It is also, as an example, the behavior required by the ECMAScript
 specification.

Heh.  Because Javascript does it is supposed to be an argument for? ;)


 In any case, my point was simply that 1/0 is not NaN.  If you're going to
 return a defined value as the result of 1/0, you should return +Infinity
 instead.

Mathematically, 1/0 is not +Infinity.  It's undefined/indeterminate in the
set of rational numbers.  The IEEE may say otherwise.

So here's a big question.  Should Perl's core maths conform to IEEE or
mathematics?  (Not something I expect an answer to.)


 NaN is used for other purposes, such as square roots of negative
 numbers when complex numbers are not available, or as the return value
 of failed numeric coercions, or of operations where even as a limit the
 result is indeterminate, such as 0/0.

So NaN means this equation might have an answer, just not in your current
set of numbers and it means a coercion failed and it means the limit is
indeterminate?  A lot of meanings.  But it doesn't mean 1/0?


This gets into questions of how Perl's math systems are extended/overridden.
Something better suited to guys like Tels I guess.  While I'd personally
like built-in support for automatic bignum conversion, I suppose the best
answer I could expect right now would be Perl 6's support for additional
maths will be greater than or equal to Perl 5.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
I'm a man, but I can change... if I have to.
-- Red Green



Re: Fw: perl6 operator precedence table

2002-10-09 Thread Michael G Schwern

On Tue, Oct 08, 2002 at 06:07:09PM -0700, Larry Wall wrote:
 I've always wondered what the ! postfix operator means.  The mathematicians
 think they know.   :-)

The Ruby folks think they know.  They're method name conventions.

From Programming Ruby

Methods that act as queries are often named with a trailing '?', such
as instance_of?.  Methods that are 'dangerous' or modify the receiver,
might be named with a trailing '!'.  For instance, String provides
both a chop and a chop!.  The first one returns a modified string;
the second modifies the receiver in place.  '?' and '!' are the only
weird characters allowed as method name suffixes.

So...

sorted_array = array.sort   # return a sorted array
array.sort! # sort in place
is_sorted = array.sorted?   # return true if the array is sorted

Interestingly enough, Ruby also supports the ?: operator as Perl does and
does not require whitespace between the tokens.

 $foo=1?42:0;   # $foo will have 42 in it.

I believe that ? simply binds tighter to method names than the ?:
operator.

This is fine:

print defined? $foo;

This is a syntax error:

print defined? $foo : 42;

/home/schwern/tmp/foo.rb:1: parse error
print defined? $foo : 42;
 ^


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Cottleston, Cottleston, Cottleston Pie.
Why does a chicken, I don't know why.
Ask me a riddle and I reply:
Cottleston, Cottleston, Cottleston Pie.



Re: Interfaces

2002-10-08 Thread Michael G Schwern

On Sun, Oct 06, 2002 at 06:17:37PM -0400, Daniel B. Boorstein wrote:
 I think there may be some confusion here. In java, there's no special syntax 
 to declare a method an optional part of the interface. All concrete classes 
 that implement the Collection interface still must define full-bodied 
 Cadd(Object element) methods. It just so happens that by convention some 
 classes simply throw an UnsupportedOperationException, perhaps like so:

A!  No wonder I couldn't find any syntax for it!  Thanks for clearing
that up.

Still, the objections still hold, though now it's a stylistic objection
rather than syntactic.  It's disturbing that they'd put these optional
methods into the core Java API, thereby encouraging their use (Sun did it,
so I can to!).  Cannonizing the idea weakens the whole concept of an
interface and contract.

It really ought to be one of those sure you can do this, but please don't
things.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
You see, in this world there's two kinds of people.  Those with loaded
guns, and those who dig.  Dig.
-- Blondie, The Good, The Bad And The Ugly



Re: Interfaces

2002-10-08 Thread Michael G Schwern

On Sun, Oct 06, 2002 at 11:57:51PM -0400, Noah White wrote:
   I wouldn't call it a dirty little secret as Michael put it :-).  
   This is the right thing to do within the context of a contract. The 
 contract does not guarantee that method functionality implemented by a 
 concrete class does exactly a certain thing a certain way ( I'd like to see 
 the language that does!).

Oddly enough, JUnit (and in the Perl world Test::Class and Test::Unit) can
do it with inherited tests.  Subclasses must pass their parent's tests, so
yes, you can guarantee method implementations, just not with an interface
contract.

Unfortunately, Java doesn't ship with JUnit nor do Java libraries usually
ship with tests nor does a simple convention to run them nor an expectation
that the user will run the tests before installing.  Score one for Perl. :)


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Please Captain, not in front of the Klingons.



Re: Interfaces

2002-10-08 Thread Michael G Schwern

On Tue, Oct 08, 2002 at 05:03:26PM -0400, Trey Harris wrote:
  It really ought to be one of those sure you can do this, but please don't
  things.
 
 It's a RuntimeException.  You can't require that all RuntimeExceptions be
 declared if thrown;
snip
 You can subclass RuntimeException.  So if Sun hadn't provided an
 UnsupportedOperationException, anyone else could easily have done so.

I'm not objecting to the fact that it's a runtime exception [1] or that it's
possible to do such a thing.  I'm objecting to the fact that it's an
exception at all since it adds uncertainty into what should otherwise be a
guaranteed interface and that this uncertainty is put in the core library of
the language.

Because Sun did it it's now Officially OK, even if that's not what they
ment.  More so in the Java world than in Perl, things you do in the core API
become canonized. Because that's how Sun does it carries a lot of weight.
In Perl it's often that's how (C|Bourne Shell|$popular_module) does it.

Programmers parroting the design of a popular API is common and can be used
for Good or Evil.


[1] It would be less worse [2] as a compile-time exception.
[2] This is different than better. ;)

-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
I don't get it.  Must be art.



Re: Interfaces

2002-10-06 Thread Michael G Schwern

On Sun, Oct 06, 2002 at 01:49:26AM -0400, Noah White wrote:
 OTOH, Java interfaces have a loophole which is considered a design 
 mistake.
 An interface can declare some parts of the interface optional and then
 implementors can decide if they want to implement it or not.  The 
 upshot
 being that if you use a subclass in Java you can't rely on the optional
 parts being there.
 
 Say what?!? I don't think so. If a JAVA class which implements an 
 interface does not declare all of the methods of the interface then 
 that class will be abstract and you won't be able to instantiate a 
 concrete instance of it. You are guaranteed that any concrete instance 
 of a class which implements an interface will contain ALL methods 
 defined by the interface.

This came up durning a talk at JAOO by Kevlin Henny entitled Minimalism: A
Practical Guide to Writing Less Code which is a nice talk, Java or not.
http://www.two-sdg.demon.co.uk/curbralan/papers.html

Slide 7, which is about obeying contracts, says:

Subclassing and implemented interfaces should follow substitutability

Unsupported operations or operations that do a 
little less or expect a little extra add complexity

and he went off on a short tangent during the talk about optional operations
in Java.

It is possible in Java to declare methods to be an optional operation.
This means the subclass may or may not implement that method and if you try
to use an unimplemented method an UnsupportedOperationException is thrown.

Effectively, this means that for every optional method you want to use,
you've got to wrap it in a try block to catch the
UnsupportedOperationException, recover and try to do something else if it's
not there.  Makes using an optional operation complicated and error prone.

In effect, an optional interface is declaring this method may or may not
exist which ain't that useful.

I can't find the syntax or this or when it was introduced, might be 1.2, but
I see it mentioned in the Collection API and tutorial docs:

http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html

The Collection interface is shown below:
public interface Collection {
// Basic Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element);// Optional
boolean remove(Object element); // Optional
Iterator iterator();

http://java.sun.com/docs/books/tutorial/collections/interfaces/

To keep the number of core collection interfaces manageable, the JDK
doesn't provide separate interfaces for each variant of each collection
type. (Among the possible variants are immutable, fixed-size, and
append-only.) Instead, the modification operations in each interface are
designated optional: a given implementation may not support some of
these operations.  If an unsupported operation is invoked, a collection
throws an UnsupportedOperationException .  Implementations are
responsible for documenting which of the optional operations they
support.  All of the JDK's general purpose implementations support all
of the optional operations.

http://java.sun.com/j2se/1.4.1/docs/api/java/util/Collection.html

Method Summary

 boolean add(Object o)
  Ensures that this collection contains the specified element 
  (optional operation).

 boolean addAll(Collection c)
  Adds all of the elements in the specified collection to this 
  collection (optional operation).

 void clear()
  Removes all of the elements from this collection (optional 
  operation).

 boolean contains(Object o)
  Returns true if this collection contains the specified element.


I don't know basic Java syntax worth a damn, but I know its dirty little
secrets. ;)


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
It's Absinthe time!



Re: Private contracts?

2002-10-04 Thread Michael G Schwern

On Fri, Oct 04, 2002 at 08:21:55PM -0400, Trey Harris wrote:
  I can see too many problems with that technique, I think one was
  already mentioned where subclasses can unintentionally weaken
  preconditions to the point of eliminating them.  I'm sort of casting
  about looking for another way.
 
 Could you illustrate a case?  I don't know what you're talking about.
 It's completely valid to eliminate a precondition, because true is the
 weakest possible precondition.

I thought someone had posted an example, but now I can't find it and I can't
remember what it was.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
It sure is fun masturbating.
http://www.unamerican.com/



Private contracts?

2002-10-03 Thread Michael G Schwern

I've been mucking about a bit more with this whole interface thing.

So if we make method signatures only enforced on subclasses if the parent
class or method has the interface property...

except private methods, obviously.

And if we make pre/post conditions and class invariants always enforced...

shouldn't we have private invariants and conditions?


class Car is interface {
  attr wheels;  
  invar { .wheels == 4 }
  
  method accel($how_fast);
  method turn($direction, $how_sharp);
}

class ATV is Car, interface {
  attr _tilt is private;
  invar { ._tilt = 20 } is private;
  
  method turn($direction, $how_sharp) {
 pre  { $how_sharp = 20 } is private;
 ...implementation...
  }
}

I've implemented an ATV where I've put in a saftey protection against
rolling over in a turn as both an invariant and a pre-condition.  It will
not allow you to turn the car too sharply, else it simply blows up.  Wait
second... ;)

But I don't want my subclasses to be constrained by that.  It's just an
implementation detail that I only wish to enforce upon ATV and not it's
children.  So they're private.

Makes sense, no?


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Remember, any tool can be the right tool.
-- Red Green



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 02:46:38PM -0400, Michael G Schwern wrote:
 class ATV is Car, interface {

Hmmm.  That should probably be

   class ATV isa Car is interface {


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Help, help!  A Heffalump, a Horrible Heffalump!  Help, help, a Herrible 
Hoffalump!  Hoff, Hoff, a Hellible Horralump!



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 03:45:33PM -0500, Allison Randal wrote:
 On Thu, Oct 03, 2002 at 03:00:21PM -0400, Michael G Schwern wrote:
  On Thu, Oct 03, 2002 at 02:46:38PM -0400, Michael G Schwern wrote:
   class ATV is Car, interface {
  
  Hmmm.  That should probably be
  
class ATV isa Car is interface {
 
 That's:
 
 class ATV is Car is interface {

Wouldn't this mean that class names and property names will inevitably
clash, so you can't have a class and a property with the same name?


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
The key, my friend, is hash browns.
http://www.goats.com/archive/980402.html



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 03:59:08PM -0400, Mike Lambert wrote:
 With pre/post conditions, a subclass is allowed to weaken the
 preconditions or strengthen the postconditions.

How exactly does one weaken a precondition?


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Home of da bomb



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 04:54:13PM -0500, Garrett Goebel wrote:
 Garrett Goebel:
  Michael G Schwern:
   But I don't want my subclasses to be constrained by that.  
   It's just an implementation detail that I only wish to
   enforce upon ATV and not it's children.
 
 implementation details don't belong in interfaces

It's encoded as a private condition, so it's not part of the interface.

I see class invariants and conditions as just powerful, well organized
assertions, so naturally I'm going to want to use them for more than just
specifying an interface contract.  In this case, I'm using them to ensure
that internal details of my implementation are kept in order.  It would be
silly to have to define a whole new syntax for that purpose, so I just make
them private.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
The eye opening delightful morning taste of expired cheese bits in sour milk!



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 05:23:08PM -0500, Jonathan Scott Duff wrote:
 I don't know, but I think it's supposed to be like this:
 
   # part of the signature
   method turn($dir,$ang) is pre { $ang = 20 } {
   ...
   }
 
   # part of the implementation
   method turn($dir,$ang) {
   PRE { $ang = 20 }
   ...
   }
 
 turn() methods of derived classes would inherit the precondition in the
 first case but not the second. I don't know why you'd want to do this
 exactly, but it seems to me that perl should allow it.

I see us already smashing too many things into the method signature as it
is.  It will rapidly get messy if you have a method with a complex signature
and a handful of attributes and preconditions.

Also, where do the postconditions go?  In the signature at the front?  That
doesn't make sense, it should go at the end so you can keep them in mind
when you're writing the return code.

Consider...

   method foo($this, $that) is memoized is something
is pre { $this = 42 }
is pre { $that == $this / 2 }
is pre { a lot of code which is hard to
 shove into a block of code
 this close to the right margin }
is post { what is a post condition
  doing at the front? }
   {
   ...
   }

They can, of course, be pulled back from the margin:

   method foo($this, $that) is memoized is something
   is pre { $this = 42 }
   is pre { $that == $this / 2 }
   is pre { now we have a little bit more room to play with using
a differnt indentation style }
   is post { but post conditions are still distanced from the
 code which return()s }
   {
   ...
   }

I realize that conditions are technically part of the signature, but putting
them in there paints us into a stylistic corner.

I'm also not fond of the pre/PRE distinction.  Few of the other special
blocks (given, eval, try, invar, etc...) use all cap names.  At least I hope
not.  Simply attaching an is private attribute to a pre condition block
seems the simplest way to go about it.  Just like any other private thing,
it's not inherited and not visible outside the current class.  pre vs
PRE doesn't convey that meaning.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
AY!  The ground beef, she is burning my groin!
http://sluggy.com/d/990105.html



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 02:29:57PM -0700, Michael Lazzaro wrote:
 Do you think it's sufficiently clear to newbies that the pre { } is 
 associated with the signature of the turn() interface method, and not 
 just the _implementation_ of turn() in Vehicle?

The rule would be pretty simple to teach and remember, conditions and
invariants are inherited unless made private.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
It's Flypaper Licking time!



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 05:30:49PM -0400, Trey Harris wrote:
 In a message dated Thu, 3 Oct 2002, Michael G Schwern writes:
 
  On Thu, Oct 03, 2002 at 03:59:08PM -0400, Mike Lambert wrote:
   With pre/post conditions, a subclass is allowed to weaken the
   preconditions or strengthen the postconditions.
 
  How exactly does one weaken a precondition?
 
 You weaken a precondition by adding ORs; you strengthen a postcondition by
 adding ANDs.

As expressions in Perl run a tad beyond simple boolean logic, could you give
a concrete example?


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
My beverage utensil experiences a volume crisis.



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 04:47:26PM -0500, Garrett Goebel wrote:
  And if we make pre/post conditions and class invariants 
  always enforced...
 
 no. 
 
 post-conditions and invariants are always enforced, but pre-conditions are
 different.

Right, right.

 A derived interface can loosen input constraints... so it must be
 able to either satisfy all inherited pre-conditions _or_ its own
 pre-conditions.

Looking around, this seems to be regarded as something of a compromise
because truly determining what a real logical weaking is is hard.  Are there
other ways to do it, just to mull them over?


  shouldn't we have private invariants and conditions?
 
 no. 

Ummm, why?


 I should inject that I disagree with the use of term private as meaning
 non-inheritable. I think of private as an methods and attributes accessible
 only within the namespace of that class or its descendants.

Isn't that protected?

As I understand it, Perl 6's private will be non-inheritable methods
accessable only inside the class which defined it.  Ruby does it this way,
AFAIK.


 Perhaps a better
 term would be something like:
 
   method foo is disinherited { ... }

is disowned
is get_a_haircut_and_a_job
is i_have_no_son

;)


 I also need to separate out the DBC topic from the interface one. For
 instance I have a hard time thinking about attributes in the context of
 interfaces. For me, interfaces should be limited to a bunch of abstract
 methods with conditions. Any other declarations within an interface IMO
 should be errors. I.e., all other declarations belong in the implementation
 class...

I hope we're not going to explicitly seperate interfaces from
implementation.  ie. That you can define an interface at the same time as
you implement it.  This is something I really like about Perl as opposed
to other OO systems, class definition and implementation are not kept
seperate.

class Human is interface {
 attr head, shoulders, knees, toes;
 invar { .head == 1 }
 invar { .shoulders == 2 }
 invar { .knees == 2 }
 invar { .toes == 10 }
 
 method talk ($say,$how_loud) {
$say.uc if $how_loud = 10:
print $say\n;
 }
}

Of course, if interfaces in the Java sense are just classes with no
implementation details, there's no reason why you can't do it seperately.

class AbstractHuman is interface {
 attr head, shoulders, knees, toes;
 invar { .head == 1 }
 invar { .shoulders == 2 }
 invar { .knees == 2 }
 invar { .toes == 10 }
 
 method talk ($say,$how_loud);
}

class Human isa AbstractHuman {
 method talk ($say,$how_loud) {
$say.uc if $how_loud = 10:
print $say\n;
 }
}

The above would result in the same thing.  The latter explicitly seperates
the interface from the implementation, as some like, while the former does
them all in one class, as others like.


 If you want to have a public and private inheritable interfaces that's
 fine. But what's the point of a non-inheritable interface? Myself, I call
 non-inheritable methods functions.

Interface is not quite simply the union of method signature,
conditions and invariants.  Interfaces are a combination of the three,
true, but it's only a subset of their use.  They're all useful beyond simply
enforcing how subclasses are designed and implemented.

Method signatures are obviously used to define how methods are to be called
by outside users of the object, as well as change the contexts in which the
arguments are parsed.

Pre/post conditions and invariants, when private (ie. not inherited) can be
used like assertions, guaranteeing that internal state and implementation
details are kept sane.  My ATV example may not have been clear enough in
that I considered the tilt check to be an internal state check and not a
documented feature of the object.  A clearer example might be something like
checking that an internal data structure used by the object is not circular.
A class invariant, yet not something I want to enforce on my children.

They're tools that when combined form an interface but are still useful
seperately.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
The key, my friend, is hash browns.
http://www.goats.com/archive/980402.html



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 06:46:14PM -0400, Michael G Schwern wrote:
 I see us already smashing too many things into the method signature as it
 is.  It will rapidly get messy if you have a method with a complex signature
 and a handful of attributes and preconditions.

I think I have my own counter example.

Consider defining an abstract class with an interface and I want to put some
conditions onto an abstract method.

 class Abstract::Human is interface {
 attr head, shoulders, knees, toes;
 invar { .head == 1 }
 invar { .shoulders == .knees == .toes == 2 }
 
 method eat ($food) is pre  { !$food.isa('Poison') }
is post { .return eq 'Burp' }
 }

since I have no method body for eat() I have no choice but to hang it off
the signature as an attribute.

So conditions do have to go on the signature, but I still like the option of
their being in the body as well, especially given the problem of wanting to
put post conditions at the end.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Cottleston, Cottleston, Cottleston Pie.
A fly can't bird, but a bird can fly.
Ask me a riddle and I reply:
Cottleston, Cottleston, Cottleston Pie.



Re: Private contracts?

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 07:23:14PM -0400, Michael G Schwern wrote:
invar { .shoulders == .knees == .toes == 2 }

This may explain why I can only count to 12 with my shoes off.

As this is my 3rd reply to myself in the thread, I'll call it a night. :)


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
If the women don't find you handsome, they should at least find you handy.
-- Red Green



Re: Delegation syntax? (was: Re: Private contracts)

2002-10-03 Thread Michael G Schwern

On Thu, Oct 03, 2002 at 07:59:33PM -0600, John Williams wrote:
 Reaction #2:  Inheritance would automatically delegate all those
 methods, so again, in what way does inheritance _not_ solve the problem?

I don't think p6l is the right place to discuss the merits of delegation,
let's just say it's a Good Thing to have in your OO toolbelt.  Solves a lot
of problems which would otherwise require hairy, ambiguous multiple
inheritance situations.  If you're curious I can explain more off-list.


 Finally, a question about interfaces:
 In what way is an interface different from a pure abstract class (i.e.
 containing only method declarations, but no code)?

An interface requires subclassers to implement all abstract methods and they
must match the method signatures, conditions and invariants of the
interface.

A pure abstract class doesn't necessarily require subclasses to do anything,
at least not in Perl.

So an interface is simply a class, maybe abstract, which requires its
subclasses to conform to its signature.

At least that's how I see it.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
It's Airplane Glue sniffing time!



Re: Delegation syntax?

2002-10-03 Thread Michael G Schwern

On Fri, Oct 04, 2002 at 12:28:29AM -0400, Trey Harris wrote:
 I think my point here is that there are clearly places where we need
 stronger built-in support in Perl of some OO concepts.  Delegation may not
 be one of them--it's easy enough to graft on, and TMTOWTDI may be good
 here.

Delegation is a basic OO technique.  We definately should have fast,
well-designed core support for it.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Is there an airport nearby or is that just my tae-kwon-do taking off?



Re: Interfaces

2002-10-02 Thread Michael G Schwern

On Tue, Oct 01, 2002 at 05:04:29PM -0700, Michael Lazzaro wrote:
 On Tuesday, October 1, 2002, at 02:49  PM, Michael Lazzaro wrote:
 Which implies, I assume, that interface is not the default state of 
 a class method, e.g. we do need something like method foo() is 
 interface { ... } to declare any given method
 
 Flippin' hell, never mind.  You're almost certainly talking about a 
 style like:
 
   interface Vehicle {
   method foo () { ... }
   method bar () { ... }
   }

Definately not that.

 - or -
   class Vehicle is interface {
   ...
   }


snip

   class Vehicle {
   method foo () is interface { ... }
   method bar () is interface { ... }
   method zap () is private { ... }
   }

Perhaps both of the above, but only if methods-as-interfaces have to be
explicitly declared.  I like the class Vehicle is interface as a shorthand
for declaring every method of a class to be an interface.

It depends on if method signatures are enforced on subclasses by default, or
if you have to explicitly declare yourself to be an interface.  That's up in
the air in my mind.

Orthoginal to that decision is if a subclass should be able to explicitly
ignore its parent's interface and conditions.  I started by leaning towards
yes, now I'm thinking no.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Plus I remember being impressed with Ada because you could write an
infinite loop without a faked up condition.  The idea being that in Ada
the typical infinite loop would be normally be terminated by detonation.
-- Larry Wall in [EMAIL PROTECTED]



Re: Interfaces

2002-10-02 Thread Michael G Schwern

On Tue, Oct 01, 2002 at 04:01:26PM -0700, Michael Lazzaro wrote:
 On Tue, Oct 01, 2002 at 03:43:22PM -0400, Trey Harris wrote:
 You want something like
 
   class Car is Vehicle renames(drive = accel)
 is MP3_Player renames(drive = mp3_drive);
 
 I *really* like this, but would the above be better coded as:
 
   class Car is Vehicle renames(drive = accel)
   has MP3_Player renames(drive = mp3_drive);
 
 ... implying a container relationship with automatic delegation?  

That would simply be another way to do it.  One is multiple inheritence, the
other is delegation.  Both should be in the language.


 Among the other considerations is that if you simply said
 
   class Car is Vehicle has MP3_Player;
 
 the inheritance chain could assume that Car.drive === Vehicle.drive, 
 because is-a (inheritance) beats has-a (containment or delegation).  If 
 you needed to, you should still be able to call $mycar.MP3_Player.drive 
 to DWYM, too.

This, too, is another way to do it, but I like Trey's original solution much
better.  When you use your MP3 Car as a Vehicle, the Vehicle methods win.
When you use it like an MP3_Player, the MP3_Player methods win.  No need to
expose the underlying MP3_Player object to the user.  YMMV.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
List context isn't dangerous.  Misquoting Gibson is dangerous.
-- Ziggy



Re: Interfaces

2002-10-02 Thread Michael G Schwern

On Tue, Oct 01, 2002 at 02:49:49PM -0700, Michael Lazzaro wrote:
 My musing is that the behavior of a class in different contexts is
 itself an interface, in the sense of being a contract between a
 class/subclass and it's users
 
 Ah HA!  Contract!  Return values can be enforce via a simple DBC post
 condition, no need to invent a whole new return value signature.
 
 I think I get it, but can you give some pseudocode? If you want a 
 method to return a list of Zoo animals in list context, and a Zoo 
 object in Zoo object context, what would that look like?

The trick is having some way of getting at the return value. Class::Contract
does this by having a magic value() function you can call in a
post-condition.  I can't think of anything better, so...

class Animals;
method zoo {
   ...
   
   # I have no idea what actual post condition syntax will look like
   post {
   given want {
   when 'LIST' { grep { $^thing.isa('Zoo::Animal') } value() }
   default { value().isa('Zoo') }
   }
   }
}

It might be nice if the return value was the topic of the post condition,
but that leads to problems of how you deal with lists as topics which I
don't know if they've been solved.


 (I'm assuming that DBC postconditions on a method would be treated, 
 internally, as part of the overall signature/prototype of the method: 
 i.e. if you override the method in a subclass, all original 
 postconditions would still remain attached to it (though the new method 
 might itself add additional postconditions.))

That's how I understand it works.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
I'm a man, but I can change... if I have to.
-- Red Green



Re: Interfaces

2002-10-01 Thread Michael G Schwern

On Tue, Oct 01, 2002 at 03:43:22PM -0400, Trey Harris wrote:
 You want something like
 
   class Car is Vehicle renames(drive = accel)
 is MP3_Player renames(drive = mp3_drive);
 
 Either of those renamings is, of course, optional, in which case drive()
 refers to the non-renamed one when referring to a Car object.
 
 But later on, if some code does
 
   Vehicle $mover = getNext(); # returns a Car
   $mover.drive(5);
 
 It should call CVehicle::drive() on C$mover, that is,
 C$mover.accel().
 
 See why aliasing doesn't solve this?

Ahh, because Perl has to know that when $mover is used as a Vehicle it
uses Car.accel but when used as an MP3_Player it calls Car.mp3_drive.
Clever!


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
If I got something to say, I'll say it with lead.
-- Jon Wayne



Re: Interfaces

2002-09-30 Thread Michael G Schwern

On Mon, Sep 30, 2002 at 10:12:48AM -0700, Michael Lazzaro wrote:
 Heck, I'll jump into this one, since I've been working in _way_ too 
 many OO variations lately, some of them inflicted upon myself.  While I 
 hope perl6 will allow extendable OO methodologies, the out-of-box one 
 needs to be as robust as possible.  Here's a strawman opinion we can 
 argue against:
 
 I originally thought I was going to argue that it should be the default 
 behavior (to avoid yet more cruft in the method prototype) but thinking 
 about it more, I'll make the case that yes, you should have to say is 
 interface, if that's what you mean.
 
 The reason being private methods; while the interfaces to an object 
 must remain consistent, I don't think we should enforce the same rigor 
 on internal methods of a class.

Internal methods would simply be declared private and not be inherited, so
its not a problem.

method _do_internal_init ($num) is private {
   ...
}

Last I heard, Perl 6 will have basic privacy enforcement, something like the
above.


 Will interfaces be ignorable?
 
 ... and if we _do_ say any of the above, then they are not ignorable, 
 on pain o' death.  I'd argue there shouldn't be any way around it, 
 period, or we lose the whole point of the implied consistency.  Can 
 anyone think of a counterexample?

If I inherit from some parent which is well designed except for one really
poorly designed method.

Or maybe the parent class uses a really good name for a really silly
purpose, and I want that name back.

Or maybe I do want to deliberately have a subclass which is different than
the parent.

Or maybe the parent accidentally inherits something, perhaps via multiple
inheritence, and now I'm suck with it.

Not all subclasses are simply functional extensions of the parent.  In these
cases I should have a way to get around the interface restriction, probably
as an attribute to the overriding method.

OTOH, Java interfaces have a loophole which is considered a design mistake.
An interface can declare some parts of the interface optional and then
implementors can decide if they want to implement it or not.  The upshot
being that if you use a subclass in Java you can't rely on the optional
parts being there.

This comes down to an OO philosophy issue.  If Perl 6 wants a strict OO
style, don't put in a loophole.  If they want to leave some room to play,
put in the ability to turn some of the strictness off.


 What if a subclass adds extra, optional arguments to a method, is that 
 ok?
 
 This is the scariest question, I think...  In theory, yes, there are 
 lots of potential interfaces that would benefit from optional 
 extensions,  I've made a few.  In strict terms, though, they violate 
 the whole idea of common, invariant interface, so I never know if 
 what I've done is Acceptable, or a Shameful Hack...  anyone care to 
 make a case either way on this one?

The child's interface still supports the complete interface of the parent,
so I don't see it as a problem.  Sure beats having to write a whole new set
of method names just because you want to add an extra argument on the end.


 What about the return type?  If you're doing strict OO it would be 
 nice to
 specify the signature of the return value as well, which will get
 interesting to be able to describe totally the various ways in which a
 method can return in different contexts.
 
 While I cannot conceive what monstrosity of syntax we could put in the 
 method prototype to say I want to return this type in this context, 
 and this type in this context, etc., etc.

To paraphrase Damian at YAPC::Europe, It's Damian's problem. ;)

 Better to enforce it?  (Of course, if our 
 interface a is returning an object, of a class that flattens itself 
 differently in different contexts, then do we say the interface can 
 only return object classes derived from that first object class?

Yes.  The object class is simply a return type.


 And do we restrict the possible flattenings of the object class itself, 
 using an interface, so subclasses of the returned obj can't muck with 
 it and unintentionally violate our first interface (a)?... there's a 
 can of worms, boy...)

At that point you want to use the Design By Contract features, probably via
a class invariant, to ensure that all your subclasses flatten the same way.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
In my day, we didn't have none of yer new-fangled token-pasting
operators!  We stuck the tokens together with our BARE HANDS and we
LIKED IT.
--  Mark-Jason Dominus fondly remembers perl 1.0
in [EMAIL PROTECTED]



Interface lists (was Re: Interfaces)

2002-09-30 Thread Michael G Schwern

On Tue, Oct 01, 2002 at 01:36:19AM +0100, Simon Cozens wrote:
 [EMAIL PROTECTED] (Michael G Schwern) writes:
  method _do_internal_init ($num) is private {
 
 Just thinking aloud, would 
 sub foo is method is private is integer is fungible {
 
 be better written as
 sub foo is fungible private integer method {
 
 or not?

How about seperated by commas, like any other list?

  method foo is fungible, private, integer {


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
That's what Jagulars always do, said Pooh, much interested.  They call
'Help! Help!' and then when you look up they drop down on you.



Re: Interfaces

2002-09-30 Thread Michael G Schwern

On Mon, Sep 30, 2002 at 06:04:28PM -0700, David Whipp wrote:
 On a slightly different note, if we have interfaces then I'd really
 like to follow the Eiffel model: features such as renaming methods
 in the derived class may seem a bit strange; but they can be useful
 if you have have name-conflicts with multiple inheritance. 

I'm not familiar with the Eiffel beyond it's the DBC language and it's
French, but wouldn't this simply be covered by aliasing?

Which I guess raises the question, is a method's signature and attributes
part of the method itself, or it's name?  In other words, do aliases to the
same method carry the same signature and attributes?


 Oh yes, and we need to make sure DBC stuff is part of the interface, not
 the implementation.

Sensible.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Playstation?  Of course Perl runs on Playstation.
-- Jarkko Hietaniemi



Subject-Oriented Programming

2002-09-30 Thread Michael G Schwern

Last year at JAOO I stumbled on this thing called Subject-Oriented
Programming which looked interesting.  I dug up some papers on the subject
and tried to make an implementation but found I really didn't properly
understand it and the papers were too bogged down in C++ implementation
details to really describe it well.

So since this list is a magnet for folks who know obscure programming
techniques, is there anyone out there familiar enough with SOP that they
could lay out some examples in pseudo-perl?


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Stupid am I?  Stupid like a fox!



Interfaces

2002-09-29 Thread Michael G Schwern

Recently I presented a Perl 6 overview talk at a Java conference.  The
audience was mostly mute, which is unfortunate as I wanted to hear some
feedback or at least some groans of pain, but there was one Lisp programmer
in the front row that asked some interesting questions.

One was Perl 6 support interfaces? meaning Java style interfaces.
Figuring that we now have proper subroutine prototypes and assuming forward
declarations stayed in the language, sure we'd effectively have interfaces.
Thinking on it afterwards, there's a bit more to it that that.

If I was to declare an abstract class using interfaces in Perl 6, I'd
figure it would look something like this:

   class Toilet;

   method flush_capacity ($liters);
   method plunge ();
   method flush ();
   method fill ($liters);
   method water_height ();
   method seat_up ();
   method seat_down ();

and then all you have to do is subclass and implement those methods.  In
order for this to really be interfaces, there would have to be a few more
things.

- Overriding methods would have to have the same signature as the parent.
  If not, a warning or error would be issued.

   class Crapper isa Toilet;

   # Ok.  Variable name different, signature the same.
   method flush_capacity ($litres) {
  ...
   }

   # Ok, but illustrates that signatures will have to have types
   # to really be useful.
   method fill ($gallons) {
  ...
   }

   # Not ok.  Wrong signature.
   method plunge ($plunger) {
  ...
   }

   # Ok?  The old signature will still work, we've just added
   # an extra, optional argument. [1]
   method water_height (;$metric_or_imperial) {
  ...
   }

- Methods left unimplemented should issue a warning or error at compile-time.
  Anything left for autoloading should probably be declared as such.
  
   class Loo isa Toilet;
   
   method water_height () is autoloaded;


Here's some open problems:

Would this be the default behavior for overridden methods, or will the 
parent class/methods have to be declared is interface for the signatures
to be enforced on subclasses?

Will interfaces be ignorable?

What if a subclass adds extra, optional arguments to a method, is that ok?

What about the return type?  If you're doing strict OO it would be nice to
specify the signature of the return value as well, which will get
interesting to be able to describe totally the various ways in which a
method can return in different contexts.


[1] I don't know what Perl 6 signatures will use for optional arguments,
so I'll just use the Perl 5 style.

-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Do you have a map? Because I keep getting lost in your armpits.



Re: ( .... ) vs { .... }

2002-09-23 Thread Michael G Schwern

On Sun, Sep 22, 2002 at 10:37:59AM -0500, Me wrote:
 In several forms of courier, and some other text fonts
 I view code in, I find it hard to visually distinguish the
 pattern element:
snip

I'd suggest a clearer fixed-width font than Courier.  Perhaps Monaco, Neep
or, if you can find them, Mishawaka or ProFont.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
But let us not dwell on such unhappy things.  Let us instead think of 
pancakes--moist, delicious pancakes, dripping with syrup and hot butter.
-- http://www.angryflower.com/timelo.gif



Re: A few thoughts on inheritance

2002-08-26 Thread Michael G Schwern

On Sat, Aug 24, 2002 at 09:57:17PM -0400, Chris Dutton wrote:
 We are supposedly going to be able to set a class to be 
 uninheritable.

Err, I believe the result of that discussion was that unihertiable classes
is a Bad Idea and very easy to work around using delegation. 

http:[EMAIL PROTECTED]/msg10599.html

Experience from Java's final shows it doesn't prevent anyone from
effectively inheriting, often gets used in the wrong places and it's an
exposed premature compiler optimization.

Worse, it often gets used in wholely the wrong places.  For example: In
Java, java.lang.String, java.lang.Math and java.net.URL are all final.  This
means you can't inherit from these basic classes that you'll probably want
to inherit from.  Why?  Somebody probably figured it would run a bit faster.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
They had applied the blinders of steam-grilled hamburgers to my eyes.



Re: Perl 6, The Good Parts Version

2002-07-16 Thread Michael G Schwern

On Wed, Jul 03, 2002 at 10:52:58PM +0100, Tim Bunce wrote:
 Don't forget Apocalypse 5.

 Personally I believe the elegant and thorough integration of regular
 expressions and backtracking into the large-scale logic of an
 application is one of the most radical things about Perl 6.

How does one explain this to an audience that likely isn't convinced regexes
are all that important in the first place?  Sure it's line noise, but it's
new and improved line noise! I may have to avoid the topic of regex
improvements unless I can cover it in  5 minutes.  Maybe a quick poll of
how many people are using one of the many Perl5-like regex libraries, if
there's a high portion then talk about the new regex stuff.

Grammars, OTOH, is something I think I'll mention.

I also forgot hyperoperators.  Also it's likely worth mentioning that perl's
method call syntax will switch to the dot making it look more like other
languages.

Unicode from the ground up is probably also worth mentioning, though I'm not
quite sure what forms this will take other than Unicode will not be an
awkward, bolt-on feature.  I don't know how Java and Python handle Unicode.


-- 
This sig file temporarily out of order.



Perl 6, The Good Parts Version

2002-07-03 Thread Michael G Schwern

I've just submitted a short talk to the Scandinavian Conference on Java And
Object Orientation (JAOO.org) [1] entitled Perl 6, The Good Parts.  This
talk will be given to an audience of mostly Java, Python and Ruby
programmers with a smattering of XP  Agile methodology folks and OO and
Pattern gurus.  It will try to convince them of two things:

 Perl 6 is not a joke (anymore).
 
 The Perl 6 language, design and implementation contains
 revolutionary ideas that you should pay attention to.

I've been trying to pick out what parts of Perl 6 would make a Java
programmer sit up and go I wish I had that or a Python programmer think
Hmm, maybe there is more than one way to do it and, in fine Perl
tradition, a few things which make the whole audience go what a bunch of
fruitcakes!

Here's what I've got:

Parrot
Both as our answer to the JVM and .Net and that the language design
and the coding of the internals are going on simultaneously.

Topicalizers
Perl 5 has Do What I Mean, Perl 6 will have Ya Know What I Mean.
A language which understands the concept of it.

Community Funding
A programming community with employees.  $200,000 raised so far.

Community Design
The sometimes rocky process of design by community.

Closures, Continuations, Currying, Everything Is An Object, Multimethod
Dispatch, Slots, Introspection...
Sure, other languages have these features, but all together in one 
language?

Attributes
Transcending mere objects and classes, Perl 6 introduces adverbs.


Parrot, Funding and Design are pretty straight forward to explain to an
audience of Java programmers.  For the rest, I'm asking for help placing the
proper spin on it.  Topicalizers will be particularly tricky to explain
without making it just sound like an opportunity to write more
incomprehensible Perl code.

I'm also trying to think of more bits to throw in.  Particularly in terms of
the OO system, this being a conference about OO.  From what I've heard so
far, Perl 6's OO system will be largely playing catch up with other
languages.  Hopefully the Cabal [2] can debunk that.  What will Perl 6's
class system offer that will impress a Java programmer?


[1] I was invited to speak there last year by mistake and liked it so much
I'm trying to weasel my way in again.

[2] Of which there is none.

-- 
This sig file temporarily out of order.



Re: Perl 6, The Good Parts Version

2002-07-03 Thread Michael G Schwern

On Wed, Jul 03, 2002 at 09:20:01PM +0100, Dave Mitchell wrote:
 On Wed, Jul 03, 2002 at 01:23:24PM -0400, Michael G Schwern wrote:
   Hopefully the Cabal [2] can debunk that.
 [snip]
  [2] Of which there is none.
 
 and http://www.perlcabal.com/ doesn't exist, right? ;-)

  Not Found
  The requested URL / was not found on this server.
  TINPC/1.3.14 Server at www.perlcabal.com Port 80

*snort* :)


-- 
This sig file temporarily out of order.



Re: Ruby iterators

2002-07-02 Thread Michael G Schwern

On Fri, Jun 28, 2002 at 01:21:50PM -0700, Erik Steven Harrison wrote:
 Over on Perlmonks someone was asking about Perl 6's ability to have named
 argument passing. He also asked about the Jensen Machine and Ruby iterators.
 Now, just being on this list has taught me so much, but, I'm not quite sure
 how it works, practically speaking, and whether or not we'll get in in P6.
 (I understand the abstract o fpass by name, but not how we use it). Could
 someone explain it to me, and tell me what the Perl 6 stance on the matter
 is?

* Yes, Perl 6 will have named arguments to subroutines.

What I can remember from the Perl 6 BoF is it will look something like this:

sub foo ($this, $that) {
print $this if $that;
}

which is like:

sub foo {
my($this, $that) = @_;
print $this if $that;
}

somebody else on this list can handle explaining how that all works better
than I can.  There's stuff about pointy subroutines, -, method topics,
etc... *hand wave*

Even better, you can have small anonymous subroutines with implied
arguments.

@sorted_list = sort { $^a cmp $^b } @list;

which Perl will translate into the moral equivalent of:

my $sub = sub ($^a, $^b) { $^a cmp $^b };
@sorted_list = sort $sub, @list;

basically, it's a quick way to declare a subroutine while still having named
arguments for things like sort, map  grep.  Perl orders the arguments in
UTF8 order.

I *think* you will also be able to do this, at least I can't see why you
wouldn't be able to:

@stuff = grep { length $^foo = 42 } @list;

which is nice for nested greps and maps.  You don't have to fight over who
has $_.

So now grep/map/etc... will all take real code refs, so...


* Yes, Perl 6 will have the moral equivalent to Ruby iterators.

I'm particularly happy about the iterators, something that leapt out at me
when I learned Ruby as being very, very powerful.

For those who don't know what Ruby iterators are, you can go back through
the archives for the thread Does this mean we get Ruby/CLU-style iterators?
or an earlier thread:
http:[EMAIL PROTECTED]/msg08343.html

From what I understand, the prototyping mechanism will be extended to allow
a method to take a block/code ref at the end of it's arguments.  Correct me
if I'm wrong, but while, for and such will all just be built-in subroutines.
So one can write something like this:

 class File;
 method foreach ($file, block) {
my $fh = open $file;
while( $fh ) {
   block($_);
}
 }

 # open /usr/dict/words and print out each line.
 File.foreach '/usr/dict/words' {
 print;
 }

The block is just an anonymous subroutine passed in as the second argument
to File.foreach().  In Perl 5, it would look something like this:

 package File;
 sub foreach {
 my($file, $block) = @_;
 open(FILE, $file);
 while(FILE) {
 $block-($_);
 }
 }
 
 File-foreach '/usr/dict/words', sub {
 print;
 };

so what Perl 6 is really adding is the ability to write methods which look
like loops.


Ruby also has it's |$a| mechanism to name the arguments.  Presumably, you'll
get the same effect with the implied arguments I mentioned earlier.

File.foreach '/usr/dict/words' {
print $^line;
}

Something like that.



* What's a Jensen Machine?


-- 
This sig file temporarily out of order.



Re: More 6PAN musings: local namespaces

2002-06-15 Thread Michael G Schwern

On Sat, Jun 15, 2002 at 10:35:48PM -0400, John Siracusa wrote:
 Once nice thing about Java is the class naming convention that lets
 individual companies (or even individuals, I guess) do custom development
 that they can safely integrate with the standard Java classes and the work
 of other companies/individuals without fear of namespace clashes.  For
 example, the Acme Corporation can build a huge library of Java code under
 the com.acme.* namespace: com.acme.widget, com.acme.widget.control, etc.

Let's dump out the sack of namespace partitioning problems:

What if Acme decides it wants to release part of it's code as Open Source?
(Happens a lot).  Does it release it as Com::Acme::Text::Thing or
Text::Thing?  If the name changes, do they have to rewrite all their
existing code?  Or maybe maintain two names?

What if Acme changes it's name?  Do they stay as Com::Acme or change all
their code?  I've experienced something similar to this at a company which
was bought and the subsequent s/Old Name/New Name/ in all the copyrights and
licenses in all the code.

What if Acme Corp. and Acme Widgets Inc. both decide they want to use
Com::Acme?  What happens if lawyers get involved?

What if Acme Corp. decides it wants to enforce it's trademark on Com::Acme?


A variation on the last two already happened.  Could someone who knows the
full story relate what happened when Sun wanted to release it's core Solaris
perl modules to CPAN?  I know it involved trademarks and guaranteeing a
namespace exclusively for Sun.


It would be nice to have someone experienced with Java to relate how things
have worked out with the com.acme.* scheme.


-- 
This sig file temporarily out of order.



Implement 6PAN now with CPANPLUS shell frontends.

2002-06-05 Thread Michael G Schwern

[For those of you coming in late, here's the relevent thread from 
 perl6-language
 http:[EMAIL PROTECTED]/msg10024.html
]

Some of you may or may not be aware that I hate waiting, especially when
it's about good ideas for Perl 6.  Some of you may also be aware of the
CPANPLUS project to reimplement the CPAN shell:
http://cpanplus.sourceforge.net/

What you may not know is that CPANPLUS includes the ability to have
*multiple shell frontends*.  http://cpanplus.sourceforge.net/backend.html
Currently there's plans for two.  One mimicing the classic CPAN shell and a
new one the CPANPLUS folks are developing in their own image (the default).

Now, none of the suggestions I've seen so far in the 6PAN shell interface
thread are particularly radical and don't need to wait for Perl 6 or 6PAN.
So rather than just talking about it, DO IT!  Implement your 6PAN shell
ideas as CPANPLUS frontends.  Write an apt-get or dselect style interface to
CPAN.  Write a CPAN shell that doesn't need initial, manual configuration.
Write a pointy-clicky GUI frontend.  Experiment!

Code speaks louder than mailing list threads. :)


-- 
This sig file temporarily out of order.



Re: Half measures all round

2002-06-04 Thread Michael G Schwern

On Tue, Jun 04, 2002 at 03:53:18PM +0100, Dave Mitchell wrote:
 One word: CPAN.

For what it's worth, I'm looking forward to porting my 50-odd modules to
Perl 6.  In a lot of cases, I'll finally be able to remove some awful hacks.


-- 
This sig file temporarily out of order.



Re: 6PAN (was: Half measures all round)

2002-06-04 Thread Michael G Schwern

On Tue, Jun 04, 2002 at 10:48:06PM -0600, Luke Palmer wrote:
 Hmm... I like it. It took me a good 6 months before I learned how to use 
 CPAN. I don't see how your proposal is that different from:
 
   alias cpan='perl -MCPAN -e shell'

CPAN.pm already installs a cpan program for you that's exactly that.

schwern@blackrider:/usr/local/src/CPAN/CPAN-1.61$ cat cpan 
#!/usr/bin/perl

use CPAN;
shell;


As for the rest of the message, this all seems to already exist, in one
form or another, in the CPAN shell or CPANPLUS shell.  If you want to see a
better CPAN shell, don't wait for Perl 6!  Help the CPANPLUS folks out now!
http://cpanplus.sourceforge.net/


 But I get the idea.  Someone (well, you've inspired me now, so I) could 
 write a perl5 equivilent, because command line is quite nice.  I'll see 
 how it flies with my next class.
 
 More comments below.
 
 On Tue, 4 Jun 2002, Miko O'Sullivan wrote:
 
  [This seems like a good time to post something that's been on my mind for
  some time.]
 
 Sure. It's been pretty dull around here.
 
  DETAILS
  
  A few brief philosphical points:
  
1) People like languages that have tons of built-in
doohickeys. See PHP and Java.
 
 See Perl 5 (though PHP and Java far exceed it, in doohickeys)
 
2) Instead of a huge standard library, a really easy to use CPAN
client allows programmers to have the world of modules almost
as easily as built-in, and with the advantage of up-to-date-ness
and quantity.
 
 Indeed. And it should be _really_ easy to install to a different source 
 tree and have Perl use it. I want more modules on systems I don't 
 administrate, and asking for them is a pain.
 
  The command above would ask the user if they want to install using the
  current directory as the root of library tree, and is also mentions that if
  they want to specify another dir they can use this command:
  
 cpan --lib ~/lib load Date::EzDate
 
 Hmm... yeah, I think that's as easy as library root's gonna get. I like 
 Cinstall better than Cload, though.

snip


-- 
This sig file temporarily out of order.



Re: Idea

2002-05-22 Thread Michael G Schwern

On Wed, May 22, 2002 at 10:14:17AM -0700, Chris Angell wrote:
 I have an idea for the int() function.  I think it would be cool if it
 returned false/undefined when the argument passed to it is a whole number.
 For example:
 
 int(1) or print argument passed to int() is something other than a
 decimal number;
 
 A friend came up with this:
 
 sub myint { return if $_[0] =~ /\A\d+\z/; $_[0] =~ /^(\d+)/ ? $1 : 0 }
 
 What do you guys think?

It would be nice to have a way to check if something is an integer better
than the regexes in perlfaq4, but int()'s return value already has a job:

$ perl -wle 'print int(1.5)'
1
$ perl -wle 'print int(2)'
2

if it was changed to return 0 with integers and only truncate floats, you'd
get some very odd and unpredictable behavior:

sub int_add { return int($_[0]) + int($_[1]) }

print int_add(2.5, 2.5);   # 4
print int_add(2.0, 2.5);   # 4
print int_add(2,   2.5);   # 2!

to be safe, you'd always have to shield your int() calls where you want to
truncate.

my $truncated_num = int($num) ? int($num) : $num;


A better way, since we're hopefully going the Everything Is An Object route,
would be to simply have an is_int() method for numbers.

print $num.is_int ? Integer : Float;


-- 
This sig file temporarily out of order.



Re: Backslashes

2002-05-21 Thread Michael G Schwern

On Tue, May 21, 2002 at 11:03:42AM +0100, Nicholas Clark wrote:
 I believe that the correct rule for single quote context in perl should have
 been that backslash followed by anything is that thing.

That leaves Win32 users stuck in the same rut as now:

print 'c:\\it\'s\\going\\to\\be\\hard\\to\\read\\win32\\paths';

Read on.


 It's easier than the current one - backslash followed by backslash or the
 opening or closing delimiter is that thing, else it's backslash followed by
 that thing.  Because to parse the contents of a string with this rule, you
 have to know what delimiter is.

Here's an easier one: backslash followed by the delimiter is that thing.
Everything else is literal.

print 'c:\it\'s\easier\to\write\win32\paths\this\way';
print q{this is ok { and so is \} } C:\this };

there's no need to backwack a lone backslash in single-quote context since
there's no ambiguity.  It's trivial for the parser to figure out what the
terminating delimiter, in fact, it *has* to know else it can't terminate the
string!  So there's no extra work for the parser.

The rule can be stated here clearly: Backwack the delimiter.


-- 
This sig file temporarily out of order.



Re: Methods, and such

2002-05-16 Thread Michael G Schwern

On Wed, May 15, 2002 at 07:38:12PM -0600, root wrote:
 #BTW, is there some standard way of creating instances 
 #now?

Class::Classless and Class::Prototyped off the top of my head.




Re: Regex and Matched Delimiters

2002-04-23 Thread Michael G Schwern

On Tue, Apr 23, 2002 at 11:11:28PM -0500, Me wrote:
 Third, I was thinking that having perl 6 regexen have /s on
 by default would be easy for perl 5 coders to understand;
 not too hard to get used to; and have no negative effects
 for existing coders beyond getting used to the change.

I'm jumping in the middle of a conversation here, but consider the
problem of .* matching newlines by default and greediness.

   /(foo.*)$/,  /(foo.*)$/m  and  /(foo.*)$/s

when matching against something like foo\nwiffle\nbarfoo\n One matches the
last line.  One matches the first line.  And one matches all three lines.


-- 

Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/
Perl Quality Assurance  [EMAIL PROTECTED] Kwalitee Is Job One
Consistency?  I'm sorry, Sir, but you obviously chose the wrong door.
-- Jarkko Hietaniemi in [EMAIL PROTECTED]



  1   2   3   4   >