is Code
WhateverCode
objects are the result of Whatever
-priming. See the Whatever
documentation for details.
When you wish to control how a method or function interprets any Whatever star, you may use multi dispatch with Whatever
and WhateverCode
parameters to do so, as in the following example:
multi get-val(Cycle , Int )# Define what to do with a stand-alone * as the second argumentmulti get-val(Cycle , Whatever )# Define what to do with a * WhateverCode in an expressionmulti get-val(Cycle , WhateverCode )my Cycle .= new(:pos(2), :vals(0..^10));say get-val(, 3); # OUTPUT: «3»say get-val(, *); # OUTPUT: «2»say get-val(, *-1); # OUTPUT: «1»
The WhateverCode
does
the Callable
role, so it should be possible to introspect the type of Callable
it contains; for instance, continuing the previous example, we can add a multi that handles a WhateverCode
with two arguments via checking the signature:
# Define what to do with two * in an expressionmulti get-val(Cycle , WhateverCode where )say get-val(, * + * div 2); # 2 + 10/2 = 7
Note, though, that subexpressions may impose their own Whatever star rules:
my = (0, 1, 2);say get-val(, []) # 2, because the star belongs to the Array class
This can make the ownership of Whatever stars become confusing rather quickly, so be careful not to overdo it.
You may instead type-constrain using Callable
type in order to accept any Callable
, including WhateverCode
:
sub run-with-rand (Callable ) ;run-with-rand *.say; # OUTPUT: «0.773672071688484»run-with-rand ; # OUTPUT: «0.38673179353983»run-with-rand sub ; # OUTPUT: «0.0589543603685792»
Type-constraining with &
-sigiled parameter works equally well and is shorter to type:
sub run-with-rand () ;