Feofilakt
Feofilakt

Reputation: 1387

Cumbersome syntax for adding element to collection in F#

type myClass(property1 : Map<int, string>) =
    member val Property1 = property1 with get, set

let myObject = myClass(Map.ofList [(1, "one"); (2, "two"); (3, "three")])

I understand correctly that for adding element to property collection we should write

myObject.Property1 <- myObject.Property1.Add (5, "five")

instead of

myObject.Property1.Add (5, "five")

? There is no more concise syntax? Thanks.

Upvotes: 0

Views: 112

Answers (1)

Matthew Walton
Matthew Walton

Reputation: 9959

F# maps are immutable, so Add returns a new Map with the additional element. So if you're storing it in a class's property, yes you do have to assign the new Map to that property. There's no shortcut syntax because mutables aren't really idiomatic F#.

For this application you might find it preferable to open System.Collections.Generic and use Dictionary, which is mutable and probably more suitable for carrying around inside objects.

Upvotes: 5

Related Questions