📜  F#记录(1)

📅  最后修改于: 2023-12-03 15:15:12.892000             🧑  作者: Mango

F# Record

F# Record is a type in F# which allows us to define immutable data structures. It is similar to C# classes or structs, but with some additional features like built-in ToString(), Equals(), and GetHashCode() methods.

Creating F# Record

To create an F# Record, we use the type keyword followed by the record name and the keyword =. Then we define the record's fields and their types.

type Person = {
    FirstName: string
    LastName: string
    Age: int
}

This creates an F# Record called Person with three fields: FirstName of type string, LastName of type string, and Age of type int.

Initializing F# Record

We can initialize an F# Record using curly braces {} and assigning values to its fields.

let person = { FirstName = "John"; LastName = "Doe"; Age = 30 }

This creates a new instance of the Person record with the FirstName set to "John", LastName set to "Doe", and Age set to 30.

Accessing F# Record Fields

To access the fields of an F# Record, we use the dot notation ., similar to how we access properties of classes in C#.

printfn "%s %s is %d years old." person.FirstName person.LastName person.Age
Updating F# Record Fields

Since F# Records are immutable, we cannot modify their fields directly. Instead, we can create a new instance of the record with the updated values using the with keyword.

let updatedPerson = { person with Age = 31 }

This creates a new instance of the Person record with the Age field updated to 31. The other fields remain the same as the original person.

Pattern Matching with F# Record

F# Records can be used with pattern matching, just like other F# types. We can use the match keyword to match the fields of an F# Record and perform actions based on the matched values.

let displayAge person =
    match person with
    | { Age = age } -> printfn "Age: %d" age
    | _ -> printfn "Age not found"

displayAge updatedPerson  // Output: Age: 31
Conclusion

F# Record is a powerful tool for defining immutable data structures in F#. It provides easy ways to create, access, and update the fields of the record. Its built-in methods like ToString(), Equals(), and GetHashCode() make it convenient to use.