How can I reference an existing method in Raku?
Asked Answered
L

1

7

As explained in the docs, you can reference an existing function by prepending the & sigil:

&say       # reference to the `say` function
&infix:<+> # reference to the infix `+` operator

How do I do this for methods?

Lorikeet answered 8/7, 2023 at 13:18 Comment(0)
L
6

This article's author explains there are a few possibilities to get hold of a method object, however the most relevant one here is to use the MOP method .^lookup:

say Array.^lookup('push').raku

#`«
proto method push ($: |) {*}
»

For example to get all the candidates's signatures for Array's push method you'd do:

.say for Array.^lookup('push').candidates.map(*.signature);

#`«
(Any:U \SELF: |values)
(Array:D: Slip \value, *%_ --> Array:D)
(Array:D: \value, *%_ --> Array:D)
(Array:D: **@values is raw, *%_ --> Array:D)
»
Lorikeet answered 8/7, 2023 at 13:53 Comment(1)
"to get all the candidates's signatures" That may work for some methods but it's hit and miss in the general case. Per the current doc on lookup it "does not provide a full list of candidates ... if you're after something which can be invoked you probably want to use find_method [which] will use a default candidate for parametric roles, whereas lookup throws an exception ... and ... [find_method] honors FALLBACK methods, which lookup does not." (And I presume what is true for find_method is also true for find_method_qualified.)Marciemarcile

© 2022 - 2024 — McMap. All rights reserved.