Generics in F#
Starting with version 5.0, F# has added support for generics, which are similar to type parameters in other languages.
As an example of a generic function, slicesIndex
takes a list of any type that supports equality comparison and an element of that type, and returns the index of the first occurrence of v
in s
, or -1 if not present.
As an example of a generic type, List<'T>
is a built-in F# type that represents a singly-linked list with values of any type.
We can define functions that operate on generic types. Here’s an example of a function that pushes an element to the end of a list:
Here’s a function that returns all elements of a list:
Now let’s use these generic functions and types:
To run the program, save it as generics.fsx
and use the F# interpreter:
In F#, generics are a fundamental part of the language and are used extensively in the standard library and in user-defined types and functions. They provide type safety and code reuse, allowing you to write flexible and robust code that works with multiple types.