mind-numbing numification

Discussion in 'Perl Misc' started by Unknown Poster, Jan 29, 2004.

  1. X-No-archive: yes

    This is perl, v5.6.1 built for MSWin32-x86-multi-thread
    -----
    package Rational;

    use overload "0+" => \&float;

    # There is a subroutine called float() that, well, returns a float.
    ------
    use Rational;
    ..
    ..
    ..
    #$fraction holds an object of type Rational
    my $fsq = sqrt($fraction);
    ------------
    perl complains:
    Operation sqrt: no method found, argument in overloaded package Rational at ...

    Since sqrt() takes a numeric argument, I expected the overloading of "0+"
    to force float() to be called on the object $fraction, but it doesn't work.
    The code "my $fsq = sqrt($fraction->float());" compiles OK.
    Why isn't numification working in this case?
    Unknown Poster, Jan 29, 2004
    #1
    1. Advertising

  2. Unknown Poster

    Jay Tilton Guest

    (Unknown Poster) wrote:

    : X-No-archive: yes

    Why? Yours is a good question.

    : package Rational;
    :
    : use overload "0+" => \&float;
    :
    : # There is a subroutine called float() that, well, returns a float.
    : ------
    : use Rational;
    : #$fraction holds an object of type Rational
    : my $fsq = sqrt($fraction);
    : ------------
    : perl complains:
    : Operation sqrt: no method found, argument in overloaded package Rational at ...
    :
    : Since sqrt() takes a numeric argument, I expected the overloading of "0+"
    : to force float() to be called on the object $fraction, but it doesn't work.

    Because sqrt() is itself an overloadable operator.

    You can either let the overload pragma handle this on its own:

    use overload
    "0+" => \&float,
    fallback => 1;


    or, probably better, go ahead and overload sqrt:

    use overload
    "0+" => \&float,
    "sqrt" => sub { sqrt($_[0]->float) };
    Jay Tilton, Jan 29, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Lloyd Sheen
    Replies:
    8
    Views:
    383
    William LaMartin
    Nov 19, 2003
  2. Greg Hurlman
    Replies:
    5
    Views:
    1,923
    Greg Hurlman
    Dec 4, 2003
  3. Chris Jackson
    Replies:
    0
    Views:
    517
    Chris Jackson
    Dec 9, 2003
  4. Normie Smith
    Replies:
    0
    Views:
    352
    Normie Smith
    Apr 5, 2004
  5. Help with a numbing assignment

    , Sep 5, 2006, in forum: C Programming
    Replies:
    12
    Views:
    386
    Simon Biber
    Sep 18, 2006
Loading...

Share This Page