Factors of an integer: Difference between revisions

Line 1,290:
 
=={{header|Mercury}}==
Mercury is both a logic language and a functional language. As such there are two possible interfaces for calculating the factors of an integer. This code shows both styles of implementation. Note that much of the code here is ceremony put in place to have this be something which can actually compile. The actual factoring is contained in the predicate <code>factor/2</code> and in the function <code>factor/1</code>. The function form is implemented in terms of the predicate form rather than duplicating all of the predicate code.
 
The predicates main/2 and factor/2 are shown with the combined type and mode statement (e.g. int::in) as is the usual case for simple predicates with only one mode. This makes the code more immediately understandable. The predicate factor/5, however, has its mode broken out onto a separate line both to show Mercury's mode statement (useful for predicates which can have varying instantiation of parameters) and to stop the code from extending too far to the right. Finally the function factor/1 has its mode statements removed (shown underneath in a comment for illustration purposes) because good coding style (and the default of the compiler!) has all parameters "in"-moded and the return value "out"-moded.
The function form is implemented in terms of the predicate form rather than duplicating all of the predicate code.
 
This implementation of factoring works as follows: