Skip to content

Instantly share code, notes, and snippets.

@nenono
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nenono/a5e047ae6fd83428c8a5 to your computer and use it in GitHub Desktop.
Save nenono/a5e047ae6fd83428c8a5 to your computer and use it in GitHub Desktop.
任意型リストのsplit
let splitBy (elm:'a) (lis:'a list) =
lis
|> (Seq.fold (fun (a,b) x->if x=elm then (b::a,[]) else (a,x::b)) ([],[])) // a=処理済みリスト b=処理中リスト x=現在の要素
|> (fun (a,b)-> b::a) // 最後の要素だけTuple右辺に残ってしまっているのでリストに結合
|> List.fold (fun s xs -> (List.rev xs)::s) [] // 個別リストの反転と全体の反転
let test1 = splitBy 0 [1;2;3;0;4;5;0;6] = [[1;2;3];[4;5];[6]] // -> true
let test2 = splitBy 0 [] = [[]] // -> true
let test3 = splitBy 0 [1;0;2;0] = [[1];[2];[]] // -> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment