On 2020-05-06 William Michels via perl6-users <perl6-us...@perl.org>
wrote:
> So if the following code does useless work:
> 
> perl6 -pe '.chop' demo1.txt
> 
> why doesn't it fail with an error, "Useless use of ... in sink context
> (line 1)"?

That's a very good question!

My best attempt at an answer:

* subroutines that are "pure functions" (i.e. have no side effects)
  can be marked with the ``pure`` trait (e.g. ``sub sqrt($) is pure``
  is in the standard library)
* the parser or the optimiser (whoever notices first) will indeed emit
  the warning "useless use of ..." when they see that the result of
  calling a pure function is sunk
* but we're not calling a function, we're calling a method!
* and (currently) Rakudo can't infer the type of the object we're
  using (it could, since the return value of ``IO::CatHandle::lines``
  can be declared, and thus the type of ``$_`` in that loop could be
  inferred, but it's hard and hasn't been done yet)
* so Rakudo can't currently know what code that ``.chop`` will end up
  calling, and if it has side-effects or not
* so it can't safely warn (it would be like warning that you're not
  checking the return value of ``say``)
* yes, there is a sub version of ``chop`` (you can write ``chop($_)``
  instead of ``$_.chop``), but it just delegates to the method, so
  without full type inference and data-flow analysis we still can't
  know if the method "is pure"

Hope this helps!

-- 
        Dakkar - <Mobilis in mobile>
        GPG public key fingerprint = A071 E618 DD2C 5901 9574
                                     6FE2 40EA 9883 7519 3F88
                            key id = 0x75193F88

Reply via email to