Search code examples
f#sequences

How to get a sublist or a subsequence in F#


I am trying to truncate this sequence like you can do with arrays in F#

let sublist sequ (i:int) (n:int) = 
    let item = Seq.item(n-i) sequ
    let start = Seq.item i sequ
    let ending = Seq.item n sequ
    Seq.truncate(item) (seq{start..ending})

sublist [|25..92|] 5 10 

like it can be done here

 Array.sub [|5..20|] 3 10

Solution

  • You forgot to write the expected results.

    You can use take and skip as in the linked answer in the comments:

    let sublist sequ (i:int) (n:int) = 
        sequ |> Seq.skip i |> Seq.take (n-1)
    

    Notice that if you are dealing with arrays you can use array slices:

    [|25..92|].[5..10]  
    > 
    val it : int [] = [|30; 31; 32; 33; 34; 35|]
    
    [|5..20|].[3..10]
     > 
     val it : int [] = [|8; 9; 10; 11; 12; 13; 14; 15|]