Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting every nth Element of a Sequence

Tags:

f#

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 // corrected after Tomas' comment
    | _ -> []

Would there be a way to write this shorter?

like image 379
Alexander Rautenberg Avatar asked Jan 13 '11 03:01

Alexander Rautenberg


People also ask

How to pick every nth element in python list?

To get every nth element in a list, a solution is to do mylist[::n].

How do you print every nth element from an array?

To get every Nth element of an array:Declare an empty array variable. Use a for loop to iterate the array every N elements. On each iteration, push the element to the new array. The final array will contain every Nth element of the original array.

How do you find the nth element of a vector in R?

The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration. It accesses the element at the index of the given vector based on these constraints, and then appends it to a sequence object.


1 Answers

Seq.choose works nicely in these situations because it allows you do the filter work within the mapi lambda.

let everyNth n elements =
    elements
    |> Seq.mapi (fun i e -> if i % n = n - 1 then Some(e) else None)
    |> Seq.choose id

Similar to here.

like image 165
Stephen Swensen Avatar answered Sep 21 '22 15:09

Stephen Swensen