F# Immutable variable sized window data structure

前端 未结 2 1354
轮回少年
轮回少年 2021-01-14 17:08

I have below a description of a data structure I need and I want to implement it using immutable data structures. I\'m trying to determine... is there an existing data struc

2条回答
  •  庸人自扰
    2021-01-14 18:05

    Thanks to Juliet's kind information, I have implemented what I need and I put it here in case anyone else might find it useful.

    let rec removeLast (s : Set<'a>, num : int) : Set<'a> = 
        match num with
        | 0 -> s
        | _ -> removeLast(s.Remove(s.MinimumElement), num-1)
    
    
    type History<'a when 'a : comparison>(underlying : Set<'a>, removal : History<'a> -> int) =
        member this.Add(x) =
            History(removeLast(underlying, removal(this)).Add x, removal)
    
        member this.Count = underlying.Count
        member this.Min = underlying.MinimumElement
        member this.Max = underlying.MaximumElement
        member this.Under = underlying
    
    let maxHist = 2
    let maxCountRemover (h : History) =
        if h.Count >= maxHist
        then h.Count - maxHist + 1
        else 0
    
    
    let testHistory =
        let s = History(Set.empty, r)
        let s = s.Add(1);
        printfn "%i: %i - %i" s.Count s.Min s.Max
        let s = s.Add(2);
        printfn "%i: %i - %i" s.Count s.Min s.Max
        let s = s.Add(3);
        printfn "%i: %i - %i" s.Count s.Min s.Max
        let s = s.Add(4);
        printfn "%i: %i - %i" s.Count s.Min s.Max
        let s = s.Add(5);
        printfn "%i: %i - %i" s.Count s.Min s.Max
        printfn "%A" s.Under
    

提交回复
热议问题