Take N elements from sequence with N different indexes in F#

后端 未结 4 1382
清酒与你
清酒与你 2021-01-18 01:50

I\'m new to F# and looking for a function which take N*indexes and a sequence and gives me N elements. If I have N indexes it should be equal to concat Seq.nth index0, Seq.n

4条回答
  •  半阙折子戏
    2021-01-18 02:39

    When you need to scan a sequence and accumulate results in O(n), you can always fall back to Seq.fold:

    let takeIndices ind sq =
        let selector (idxLeft, currIdx, results) elem =
            match idxLeft with
                | []                               -> (idxLeft, currIdx, results)
                | idx::moreIdx when idx =  currIdx -> (moreIdx, currIdx+1, elem::results)
                | idx::_       when idx <> currIdx -> (idxLeft, currIdx+1, results)
                | idx::_                           -> invalidOp "Can't get here."
        let (_, _, results) = sq |> Seq.fold selector (ind, 0, [])
        results |> List.rev
    
    seq [10 .. 20] |> takeIndices [0;5;10]
    

    The drawback of this solution is that it will enumerate the sequence to the end, even if it has accumulated all the desired elements already.

提交回复
热议问题