Here are a few examples of KC3 code. Some are original pieces for this article, some are taken from existing code.
def factorial = fn {
(0) { 1 }
(n) {
if (n > 0) do
n * factorial(n - 1)
else
1
end
}
}
Returns a list of numbers from 1 to n.
def count = fn {
(n) { count(n, []) }
(0, acc) { acc }
(n, acc) {
if n > 0 do
count(n - 1, [n | acc])
else
[]
end
}
}
Sorted lists are lists where the elements of the list are sorted.
defmodule SortedList do
def insert = fn {
([], element) { [element] }
([first | rest], element) {
if first < element do
[first | insert(rest, element)]
else
[element, first | rest]
end
}
}
end
Since the list is sorted, we can stop searching sooner if the item is absent from the sorted list.
def find = fn {
([], item) { void }
([first | rest], item) {
if item == first do
item
else
if item < first do
void
else
find(rest, item)
end
end
}
}