Course of Raku / Advanced / Containers / Scalar containers / Exercises / Integers only

Solution: Integers only

Here is a possible solution to the task.

Code

my Int $cars;

$cars = 250.7.Int;
say $cars;
say $cars.WHAT;

🦋 You can find the source code in the file integers-only.raku.

Output

250
(Int)

Comments

  1. The Int type constraint in my Int $cars makes the container reject any value that is not an integer. A direct assignment of 250.7 (a Rat) would be a compile-time error.

  2. Calling .Int on the rational value 250.7 converts it to the integer 250 by dropping the fractional part. The converted value fits the container. Make sure to not mix this behaviour with rounding.

  3. The .WHAT pseudo-method confirms that the value stored in the container is of type Int.

Course navigation

Integers only   |   Typed or untyped