concept con in category functional programming

appears as: Cons, Cons, cons
Functional Programming with Kotlin

This is an excerpt from Manning's book Functional Programming with Kotlin.

Let’s look first at the definition of the data type, which begins with the keywords sealed class. Usually, we introduce a data type with the class keyword. Here we’re declaring a class, called List, with no instance methods on it. Adding sealed in front of the class declaration means that all implementations must be declared in this file. A sealed class is also abstract by default, so can not be instantiated by itself. There are two implementations, or data constructors, of List declared next, to represent the two possible forms a List can take. As the figure shows, a List can be empty, denoted by the data constructor Nil, or it can be nonempty, denoted by the data constructor Cons (traditionally short for construct). A nonempty list consists of an initial element, head, followed by a List (possibly empty) of remaining elements (the tail).

Figure 3.1. The singly linked list, each tail links to the next list element.
Singly lined list

Just as functions can be polymorphic, data types can be as well, and by adding the type parameter <out A> after sealed class List and then using that A parameter inside of the Cons data constructor, we declare the List data type to be polymorphic in the type of elements it contains, which means we can use this same definition for a list of Int elements (denoted List<Int>), Double elements (denoted List<Double>), String elements (List<String>), and so on (the out indicates that the type parameter A is covariant—see sidebar “More about variance” for more information).

This type looks identical to our List type, except that the Cons data constructor takes explicit thunks (() -> A and () -> Stream<A>) instead of regular strict values. If we wish to examine or traverse the Stream, we need to force these thunks as we did earlier in our definition of if2. For instance, here’s an extenstion function to optionally extract the head of a Stream:

fun <A> Stream<A>.headOption(): Option<A> =
    when (this) {
        is Empty -> None
        is Cons -> Some(head()) #1
    }

As we are adding behaviour to a Stream instance, we have the h and t values available in this when smart-cast to Cons in the when construct. Note that we have to force h explicitly via h(), but other than that, the code works the same way as it would for List. But this ability of Stream to evaluate only the portion actually demanded (we don’t evaluate the tail of the Cons) is very useful, as we’ll see in the following section.