The purpose of this article is a small demonstration of how one can convert a list of one type to another type in F#. While 'Convert' is used in the header, this is really using the 'map' function and returning an entirely new list.
The below code was written in a console application
in .NET 6
type Person = {
name: string
}
type Employee = {
email: string
}
let ConvertPersonToEmployee
(person: Person) : Employee =
{
email = person.name + "@fsharp.com"
}
let ConvertPersonListToEmployeeList
(people: List<Person> option) : List<Employee> option =
match people with
| None -> None
| _ -> people.Value
|> List.map ConvertPersonToEmployee
|> Some
[<EntryPoint>]
let main argv =
let januaryJoiners : List<Person> option = Some [{ name = "Rob" }; { name = "Bob" }]
let februaryJoiners : List<Person> option = None
let januaryEmployees = ConvertPersonListToEmployeeList januaryJoiners
let februaryEmployees = ConvertPersonListToEmployeeList februaryJoiners
printfn $"January Employees: {januaryEmployees}"
printfn $"February Employees: {februaryEmployees}"
0
Output
January Employees: Some([{ email = "Rob@fsharp.com" }; { email = "Bob@fsharp.com" }])
February Employees:
Top comments (0)