# Perl 6 中的 .polymod 方法

Perl 6 中的 .polymod 方法 – 把数字分解成分母

## 命名

`.polymod` 方法接受几个除数并把它的调用者分解成一份一份的:

``````my \$seconds = 1 * 60*60*24 # days
+ 3 * 60*60    # hours
+ 4 * 60       # minutes
+ 5;           # seconds

say \$seconds.polymod: 60, 60;
say \$seconds.polymod: 60, 60, 24;

# OUTPUT:
# (5 4 27)
# (5 4 3 1)
``````

## 手工制作

``````my \$seconds = 2 * 60*60*24 # days
+ 3 * 60*60    # hours
+ 4 * 60       # minutes
+ 5;           # seconds

my @pieces;
for 60, 60, 24 -> \$divisor {
@pieces.push: \$seconds mod \$divisor;
\$seconds div= \$divisor
}
@pieces.push: \$seconds;

say @pieces;

# OUTPUT:
# [5 4 3 2]
``````

## 超越无限

``````say 120.polymod:      10¹, 10², 10³, 10⁴, 10⁵;
say 120.polymod: lazy 10¹, 10², 10³, 10⁴, 10⁵;
say 120.polymod:      10¹, 10², 10³ … ∞;

# OUTPUT:
# (0 12 0 0 0 0)
# (0 12)
# (0 12)
``````

## Zip It, Lock It, Put It In The Pocket

``````my @units  = <ng μg mg g kg>;
my @pieces = 42_666_555_444_333.polymod: 10³ xx ∞;

say @pieces Z~ @units;
# OUTPUT:
# (333ng 444μg 555mg 666g 42kg)
``````

## 快速命名

``````say ⅔.polymod: ⅓;

say 5.Rat.polymod: .3, .2;
say 3.Rat.polymod: ⅔, ⅓;

# OUTPUT:
# (0 2)
# (0.2 0 80)
# (0.333333 0 12)
``````
``````say 5.Num.polymod: .3, .2;
say 3.Num.polymod: ⅔, ⅓;

# OUTPUT:
# (0.2 0.199999999999999 79)
# (0.333333333333333 2.22044604925031e-16 12)
``````

## 使用 Number::Denominate 模块

Number::Denominate

``````use Number::Denominate;

my \$seconds = 1 * 60*60*24 # days
+ 3 * 60*60    # hours
+ 4 * 60       # minutes
+ 5;           # seconds

say denominate \$seconds;
say denominate \$seconds, :set<weight>;

# OUTPUT:
# 1 day, 3 hours, 4 minutes, and 5 seconds
# 97 kilograms and 445 grams
``````

``````say denominate 449, :units( foo => 3, <bar boors> => 32, 'ber' );

# OUTPUT:
# 4 foos, 2 boors, and 1 ber
``````

原文作者：焉知非鱼
原文地址: https://www.jianshu.com/p/cfa13a665d4b
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。