Variadic fixed-point combinator: Difference between revisions
Content added Content deleted
m (→{{header|Phix}}: Now documented, added disclaimer) |
(New post.) |
||
Line 131: | Line 131: | ||
{{out}} |
{{out}} |
||
<code>[0,1,2,0,1,2,0,1,2,0,1]</code> |
<code>[0,1,2,0,1,2,0,1,2,0,1]</code> |
||
=={{header|Java}}== |
|||
Note that the yCombinator is defined strictly correctly, that is, its variable name does not appear inside the definition. |
|||
<syntaxhighlight lang="java"> |
|||
import java.util.function.BiFunction; |
|||
import java.util.function.Function; |
|||
public final class VariadicFixedPointCombinator { |
|||
public static void main(String[] args) { |
|||
Function<Integer, Integer> fibonacci = yCombinator( |
|||
function -> n -> ( n <= 2 ) ? 1 : function.apply(n - 1) + function.apply(n - 2)); |
|||
Function<Integer, Integer> factorial = yCombinator( |
|||
function -> n -> ( n <= 1 ) ? 1 : n * function.apply(n - 1)); |
|||
BiFunction<Integer, Integer, Integer> collatz = uncurry(yCombinator( |
|||
function -> n -> c -> ( n == 1 ) ? |
|||
c : ( n % 2 == 0 ) ? |
|||
function.apply(n / 2).apply(c + 1) : function.apply(3 * n + 1).apply(c + 1) |
|||
)); |
|||
BiFunction<Integer, Integer, Integer> ackermann = uncurry(yCombinator( |
|||
function -> m -> n -> ( m == 0 ) ? |
|||
n + 1 : ( n == 0 ) ? |
|||
function.apply(m - 1).apply(1) : function.apply(m - 1).apply(function.apply(m).apply(n - 1)) |
|||
)); |
|||
for ( int value = 1; value < 5; value++ ) { |
|||
System.out.println("fibonacci(" + value + ") = " + fibonacci.apply(value)); |
|||
System.out.println("factorial(" + value + ") = " + factorial.apply(value)); |
|||
System.out.println("collatz(" + value + ") = " + collatz.apply(value, 0)); |
|||
System.out.println("ackermann(3, " + value + ") = " + ackermann.apply(3, value)); |
|||
System.out.println(); |
|||
} |
|||
} |
|||
private static interface RecursiveFunction<T> extends Function<RecursiveFunction<T>, T> { } |
|||
private static <T, R> Function<T, R> yCombinator(Function<Function<T, R>, Function<T, R>> function) { |
|||
RecursiveFunction<Function<T, R>> recursive = w -> function.apply( x -> w.apply(w).apply(x) ); |
|||
return recursive.apply(recursive); |
|||
} |
|||
private static <T, U, R> BiFunction<T, U, R> uncurry(Function<T, Function<U, R>> function) { |
|||
return (x, y) -> function.apply(x).apply(y); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{ out }} |
|||
<pre> |
|||
fibonacci(1) = 1 |
|||
factorial(1) = 1 |
|||
collatz(1) = 0 |
|||
ackermann(3, 1) = 13 |
|||
fibonacci(2) = 1 |
|||
factorial(2) = 2 |
|||
collatz(2) = 1 |
|||
ackermann(3, 2) = 29 |
|||
fibonacci(3) = 2 |
|||
factorial(3) = 6 |
|||
collatz(3) = 7 |
|||
ackermann(3, 3) = 61 |
|||
fibonacci(4) = 3 |
|||
factorial(4) = 24 |
|||
collatz(4) = 2 |
|||
ackermann(3, 4) = 125 |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |