2. Agenda
• Introduction
• Types of Generic Class
• Wildcards as Type Arguments
• Constraints in Generic Types and Functions
• Examples
3. What all Generic?
• Generics allow you to write a class or method that can work
with any data type.
• Generic constructs contain at least one type parameter,
which is usually supplied by the user of the generic construct.
• It enables programmer to write code that works with a
variety of types without repeating the code for each type.
4. What all Generic?
• F# function values
• Methods
• Properties
• Aggregate types such as classes, records,
and discriminated unions can be generic.
5. Syntax & Example: Method
// Explicitly generic method.
[ static ] member object-identifer.method-name<type-parameters>
parameter-list [ return-type ] = method-body
let printFun<'T> x y =
printfn "%A, %A" x y
printFun<float> 10.0 20.0
You can also make a function generic by using the single quotation mark
let printFun (x: 'a) (y: 'a) =
printfn "%A %A" x y
printFun 10.0 20.0
Example :2Example :1
6. when we use generic functions or methods, we might
not have to specify the type arguments.
However, in case of an ambiguity, we can provide type
arguments in angle brackets as we did in the first
example.
If you have more than one type, then we separate
multiple type arguments with commas.
Points to
remember
7. Generic: Method & Class
// Explicitly generic function.
let function-name<type-parameters> parameter-list =
function-body
// Explicitly generic class, record, interface, structure,
// or discriminated union.
type type-name<type-parameters> type-definition
8. Generic: Record
// A generic record, with the type parameter in angle brackets.
type GR<'a> =
{
Field1: 'a;
Field2: 'a;
}
9. Generic : A generic class.
type C<'a>(a : 'a, b : 'a) =
let z = a
let y = b
member this.GenericMethod(x : 'a) =
printfn "%A %A %A" x y z
10. Generic : A generic class.
type genericClass<'a> (x: 'a) =
do printfn "%A" x
let gr = new genericClass<string>(“MITWPU")
let gs = genericClass( seq { for i in 1 .. 10 -> (i, i*i) } )
"MITWPU"
seq [(1, 1); (2, 4); (3, 9); (4, 16); ...]
O/P