Getting every nth Element of a Sequence

Posted by Alexander Rautenberg on Stack Overflow See other posts from Stack Overflow or by Alexander Rautenberg
Published on 2011-01-13T03:31:34Z Indexed on 2011/01/13 3:53 UTC
Read the original article Hit count: 200

Filed under:

I am looking for a way to create a sequence consisting of every nth element of another sequence, but don't seem to find a way to do that in an elegant way. I can of course hack something, but I wonder if there is a library function that I'm not seeing.

The sequence functions whose names end in -i seem to be quite good for the purpose of figuring out when an element is the nth one or (multiple of n)th one, but I can only see iteri and mapi, none of which really lends itself to the task.

Example:

let someseq = [1;2;3;4;5;6]
let partial = Seq.magicfunction 3 someseq

Then partial should be [3;6]. Is there anything like it out there?

Edit:

If I am not quite as ambitious and allow for the n to be constant/known, then I've just found that the following should work:

let rec thirds lst =
    match lst with
    | (_,_,x)::t -> x::thirds t
    | _ -> []

Would there be a way to write this shorter?

© Stack Overflow or respective owner

Related posts about F#