@head @title Defining generic types and functions @note This section is a stub. @end

We have showed how to use generic types, but not how to define them. This section explains how to define generic types. We also discuss generic functions. @h2 Defining a generic type

This is a simple generic stack type: @example class Stack<T> private var array = [] as Array<T> def create() as void end def isEmpty() as Boolean return self.array == [] end def push(o as T) self.array.append(o) end def pop() as T self.array.removeAt(-1) end end @end

You can use it like this: @example def Main() as void var s = Stack() as <Int> s.push(2) s.push(5) Print(s.pop()) -- 5 Print(s.isEmpty()) -- False end @end

Keep these things in mind when you define generic types:

@h2 Generic functions

Alore also supports generic functions and methods. They have one or more type variables associated with them. Here is a simple generic function: @example def First<T>(a as Array<T>) as T return a[0] end var ia = [3, 5] as Array<Int> var sa = ['foo', 'bar'] as Array<Str> First(ia) -- 3 First(sa) -- 'foo' @end

You can replace the type variable (T in above example) with any type when calling the function. Usually the type checker can infer the value of the type variable, but you can also give it explicitly: @example First(ai) as <Int> @end

Note that the syntax is similar to constructing instances of generic types.