我不这么认为。所以,也许:
multi clamp ($range, $value) {
given $range {
return .max when (($value cmp .max) === More);
return .min when (($value cmp .min) === Less);
}
return $value
}
my $range = (1.0 .. 9.9);
say $range.&clamp: 15.3; # 9.9
say $range.&clamp: -1.3; # 1
my $range = 'b'..'y';
say $range.&clamp: 'a'; # b
say $range.&clamp: 'z'; # y
MOP 允许直接探索 P6 系统中可用的对象。一个特别方便的元方法是.^methods,它适用于大多数内置对象:
say Range.^methods; # (new excludes-min excludes-max infinite is-int ...
默认情况下,这仅包括Range 类中定义的方法,而不包括它继承的方法。 (要获得它们,你可以使用say Range.^methods: :all。这会让你得到一个更大的列表。)
当我刚刚尝试它时,我发现它还包含许多无用的方法,名称为Method+{is-nodal}.new。所以也许改用这个:
say Range.^methods.grep: * !~~ / 'is-nodal' /;
这个网:
(new excludes-min excludes-max infinite is-int elems iterator
flat reverse first bounds int-bounds fmt ASSIGN-POS roll pick
Capture push append unshift prepend shift pop sum rand in-range
hyper lazy-if lazy item race of is-lazy WHICH Str ACCEPTS perl
Numeric min max BUILDALL)
这就是我用来引导我找到上述解决方案的方法;我有点知道方法,但用.^methods提醒我。
另一种探索可用内容的方法是文档,例如the official doc's Range page。这让我很满意:
ACCEPTS min excludes-min max excludes-max bounds
infinite is-int int-bounds minmax elems list flat
pick roll sum reverse Capture rand
比较这两个列表,排序和装袋,出于好奇:
say
<ACCEPTS ASSIGN-POS BUILDALL Capture Numeric Str WHICH append
bounds elems excludes-max excludes-min first flat fmt hyper
in-range infinite int-bounds is-int is-lazy item iterator
lazy lazy-if max min new of perl pick pop prepend push
race rand reverse roll shift sum unshift>.Bag
∩
<ACCEPTS Capture bounds elems excludes-max excludes-min flat
infinite int-bounds is-int list max min minmax pick
rand reverse roll sum>.Bag
显示:
Bag(ACCEPTS, Capture, bounds, elems, excludes-max, excludes-min,
flat, infinite, int-bounds, is-int, max, min, pick,
rand, reverse, roll, sum)
因此,由于某种原因,list、minmax 和 sum 被记录为 Range 方法,但在我的 .^methods 调用中没有列出。大概他们被称为Method+{is-nodal}.new。嗯。
say Range.^lookup('minmax'); # Method+{is-nodal}.new
say Range.^lookup('minmax').name; # minmax
是的。唔。所以我可以写:
say Range.^methods>>.name.sort;
(ACCEPTS ASSIGN-POS AT-POS BUILDALL Bag BagHash Capture EXISTS-POS
Mix MixHash Numeric Set SetHash Str WHICH append bounds elems
excludes-max excludes-min first flat fmt hyper in-range infinite
int-bounds is-int is-lazy item iterator lazy lazy-if list max min
minmax new of perl pick pop prepend push race rand reverse roll
shift sum unshift)
无论如何,希望对您有所帮助。