HomeSearch

F# Type Example: member, get and set

Use types with members and mutable fields. Create instances of the types.

Type.

Programs are built around types. A zoo wants to keep track of its animals. It maintains animal types in memory. It reuses these types for all its animals.

With types,

we group related pieces of data together. We add behavior (in functions and properties) to our types. Programs then act upon these types.

First example.

Here we introduce an Animal type. To create an animal we must specify an int for its size (this is like its constructor).

Field: The "mutable size" is a field on the Animal type. It is initialized to the value passed to the Animal at creation time.

Do: When initialized, the Animal will execute its "do" statements. Here it prints a helpful message.

Member: The Weight is a method on the Animal. It returns an int. It returns the size times 10.

F# program that uses type, member type Animal(s : int) = // Store the argument in the object. let mutable size = s // Write a helpful message. do printfn "Animal created, size = %A" size // For Weight, return size times 10, an int. member x.Weight : int = size * 10 // Create an Animal with size 5. let animal = Animal 5 // Get the Weight of the animal. let weight = animal.Weight printfn "%A" weight Output Animal created, size = 5 50

Get, set.

Properties help us control how a type is used. Here we introduce a type Box that has a Color property. With the get() and set() keywords we add accessors.

With get: We use the "with" keyword to introduce the get() accessor. This returns the value of the "color" mutable field.

And set: In F# we introduce a setter with "and set." The "and" is important. We store the argument "c" in the color field.

F# program that uses property, get, set type Box() = // A mutable color field. let mutable color : string = null // A Box has a color property with get and set. member x.Color with get() = color and set(c) = color <- c // Create a Box instance. let x = Box() // Set and get color values. x.Color <- "blue" printfn "%A" x.Color // Set another value. x.Color <- "red" printfn "%A" x.Color Output "blue" "red"

Typeof.

This is an operator that returns the System.Type instance for the specified type. We must place a type name within the angle brackets.

Here: We create a simple type called Color with one field. With typeof we get the System.Type.

F# program that uses typeof // A type with one field. type Color() = let mutable Value = null // Get typeof Color type. // ... This is an instance of System.Type. let t = typeof<Color> printfn "%A" t Output Program+Color

A review.

In F# we can use tuples and records to store data. But for important, often-used information, we use types. This gives us a way to add helpful methods and validation.TupleRecord
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.