2023-05-27
Kata in programming is a term derived from the martial arts and it denotes a form of practice designed for consistent improvement.
In functional programming language like Kotlin you have ready-to-use functions for applying on coding problems.
A list of some useful functions.
forEachIndexed()
split()
drop()
first()
toUpperCase()
toLowerCase()
joinToString()
reversed()
filter()
count()
plus()
map()
mapIndexed()
Here an example how the function can be applied to solve a problem.
fun main() {
generateSequence(0) { it + 1 }.windowed(size=3, step=10)
.take(3).toList()
.apply(::println)
// [[0, 1, 2], [10, 11, 12], [20, 21, 22]]
}
The Java way.
import java.util.*;
import java.util.stream.*;
public class Kata {
private static List<Integer> windowed(int start) {
return IntStream.range(start, start + 3).boxed().collect(Collectors.toList());
}
public static void main(String[] args) {
List<List<Integer>> sequences = IntStream.range(0, 3)
.map(i -> i * 10)
.mapToObj(Kata::windowed)
.collect(Collectors.toList());
System.out.println(sequences);
// [[0, 1, 2], [10, 11, 12], [20, 21, 22]]
}
}
The imperative way.
private static void imperative() {
List<List<Integer>> sequences = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int start = i * 10;
List<Integer> windowedSequence = new ArrayList<>();
for (int j = start; j < start + 3; j++) {
windowedSequence.add(j);
}
sequences.add(windowedSequence);
}
System.out.println(sequences);
// [[0, 1, 2], [10, 11, 12], [20, 21, 22]]
}