2024-12-21 12:46:48

An example of purely functional KC3 code

Here are a few examples of KC3 code. Some are original pieces for this article, some are taken from existing code.

Factorial

def factorial = fn {
  (0) { 1 }
  (n) {
    if (n > 0) do
      n * factorial(n - 1)
    else
      1
    end
  }
}

List.count(n)

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

Sorted lists are lists where the elements of the list are sorted.

Sorted list insertion

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

Sorted list search

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
    }
  }