Sunday, December 7, 2008

Evry Nth element of a list

For the general case, I’ve done this:

let each_nth n list = List.fold_left2
(fun acc a i -> if i mod n = 0 then a::acc else acc)
[] list (range (List.length list))

For each 4th, OlegFink suggested:

let rec fourth = function _::_::_::a::xs -> a::(fourth xs) | _ -> []

No comments: