DEV Community

Rob Mulpeter
Rob Mulpeter

Posted on

F# Convert a List of Type A to Type B with options

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
Enter fullscreen mode Exit fullscreen mode

Output

January Employees: Some([{ email = "Rob@fsharp.com" }; { email = "Bob@fsharp.com" }])
February Employees: 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)