how to partition a list by index of list

Category: visual studio fsharp

Question

Map to new space on Wed, 07 May 2014 07:40:52


this code can only partition by value of list, how to partition by index of list?

let list1,list2 = List.partition (fun x -> x < a.Length) a


成功者拿未來換現在,失敗者用現在換未來. 原來無求品自高, 機到有求先得手. She likes you.

Replies

Mr. Tines on Wed, 07 May 2014 16:37:57


There's no library function, but there are many ways to do this like

let split (index : int) (l : 'a list) =
  let l1,l2 = l
              |> List.mapi (fun i x -> (i,x))
              |> List.partition (fun (i,x) -> i < index)
  (l1 |> List.map snd, l2 |> List.map snd)

or

let split (index : int) (l : 'a list) =
  (l |> Seq.take index |> Seq.toList, 
   l |> Seq.skip index |> Seq.toList)

or

let split (index : int) (l : 'a list) = let rec step (i : int) l' l'' = match l'' with | [] -> (List.rev l', []) | h::t -> if (i < index) then step (i+1) (h::l') t else (List.rev l', l'')

step 0 [] l