Fuzion Logo
fuzion-lang.dev — The Fuzion Language Portal
JavaScript seems to be disabled. Functionality is limited.

Rosetta Code Factors of an Integer Example

From rosettacode.org:

[The following task description was taken from rosettacode.org:]

Compute the factors of a positive integer.

These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.

(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).

Note that every prime number has two factors: 1 and itself.

Code Examples

Using a loop

Code to find the factors using a loop in Fuzion would look like this:

Iterating over an Interval

Very similarly, we can iterate over an interval using for_each and a lambda expression:


When iterating over an interval, we can apply a filter to extract the factors we want to print:

Printing a Sequence

Since Sequence provides its own print function, we can use it:

Iterating Sequences using Pipe operators

The pipe operator infix ! provides an concise syntax to eagerly iterate over a Sequence.

Filters can be applied using infix &, here using a the partial application n%% which is short for x -> n%%x, i.e., a lambda that is true for factors of n

Converting Sequence to a string

When a Sequence can be concatenated to a string, it is converted to a string consisting of its elements:

Embedding code in a String

Alternatively, we can embed the expression in a string using { and }:

Repeated Execution

Finally, here is the version using a filter embedded in a string to find the factors of all integers up to 42:

Creating a routine

We can put the code into a routine factors and then call it given the argument 42.

Note that val is a field of type i32 defined within feature i32, so this gives a means to access the i32 value. One might think that i32.this could be used as well, but this is not possible since the type of i32.this is not i32, but it could be any subtype of i32 in a feature inheriting from i32.

Adding features to library feature i32

Alternatively, we can extend the standard library and add a feature factors as inner feature of i32: