Create F# record from segments in a functional way

f#, functional-programming

Solution

Somewhat straight-forward approach (a lot of allocations due to immutability):

let createEntity segments =
    ({ Numbers = []; Date = DateTime.MinValue; Name = ""}, segments)
    ||> List.fold (fun entity segment ->
        match segment with
        | Date date -> { entity with Entity.Date = date }
        | Name name -> { entity with Name = name }
        | Number num -> { entity with Numbers = num :: entity.Numbers })

I've changed `Entity` to be 'more "functional"' by using some more idiomatic types:

type Entity = {
    Numbers: int list
    Date: DateTime
    Name: string
}

Problem

What would be the best way to create a record instance from a list of discriminated union instances which represent this record's segments. I am trying to learn functional programming with F# so I would like to do it in a "functional" way without using naive switch-like pattern matching and mutable fields (that is way I wanted to use a record type) My record type: ``` type Entity = { Numbers: int[] Date: DateTime Name: string } ``` Union representing a single segment: ``` type EntitySegment = | Date of DateTime | Name of string | Number of int ``` I would like to do the following: ``` // segments could be in arbitrary order let segments = [ Number 5; Name "Foobar"; Number 8; Number 3; Date System.DateTime.Now; Number 42 ];; let myRecord = createEntity segments ``` and myRecord would be: ``` val myRecord : Entity = {Numbers = [|5; 8; 3; 42|]; Date = 2014-07-06 17:02:36; Name = "Foobar";} ```

Original source