Reputation: 21147
I'm trying to write an F# type that wraps an underlying collection of Map<int64, customType>
such that I can add items to it:
type public CandleContainer (seedCandles:System.Collections.Generic.IEnumerable<Candle>) =
let candles : Map<int64, Candle> =
seedCandles
|> Seq.map (fun x -> x.Start.Ticks, x)
|> Map.ofSeq
let candleInterval = TimeSpan.FromMinutes(1.0)
member public x.AddCandle (candle:Candle) =
candles = candles.Add(candle.Start.Ticks, candle)
member public x.GetList () : List<Candle> =
candles
|> Map.toSeq
|> Seq.map (fun (key, value) -> value)
|> Seq.toList
The problem that I'm getting is in the AddCandle method. I understand that Map.Add returns a new map with the value added and the compiler isn't complaining that I'm trying to overwrite the value of candles. However, whenever I try adding a new Candle using this method x.GetList returns an empty list. Is there a way to overwrite the old value of candles with the result of the Map.Add? Or do I just make candles a mutable value and overwrite it?
Upvotes: 0
Views: 75
Reputation: 15885
What you're looking for is the mutable
keyword and <-
operator.
Change let candles ...
to be
let mutable candles : Map<int64, Candle>
and candles = ...
to be
candles <- candles.Add(candle.Start.Ticks, candle)
. Also note that your previous use of =
where you thought replacement was occurring was actually performing an equality check, making the return type of that method bool
.
Upvotes: 2