0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

F#でHaskellのgroupByを作る

Posted at

はじめに

以前書いた記事の続きです。
次は、HaskellのData.Listライブラリには関数"groupBy"を作ります。この関数は、リスト内の隣接する値同士を条件をもとにリストのグループを作成するものです。

コード


// 条件をもとにリスト内にリストのグループを作成する
let groupBy (predicate) (list: seq<'a>) =
    let rec auxAccumulate acc = function 
        | [] -> (acc, [])
        | x :: xs when predicate (List.last acc) x -> auxAccumulate (acc @ [x]) xs
        | xs -> (acc, xs)
    let rec auxProcess = function 
        | [] -> []
        | x::xs ->
            let (head,tail) = auxAccumulate [x] xs
            head :: auxProcess tail
    auxProcess (Seq.toList list)

実行結果

groupBy (<=) "abcabcaaa" |> printfn "%A"
//実行結果: [['a'; 'b'; 'c']; ['a'; 'b'; 'c']; ['a'; 'a'; 'a']]
groupBy (<=) [1;2;3;1;2;0;4;5;2] |> printfn "%A"
//実行結果: [[1; 2; 3]; [1; 2]; [0; 4; 5]; [2]]
groupBy (<) [1;2;2;3;3;3;1] |> printfn "%A"
//実行結果: [[1; 2]; [2; 3]; [3]; [3]; [1]]
groupBy (>) [|1;2;3;1;2;3|] |> printfn "%A"
//実行結果: [[1]; [2]; [3; 1]; [2]; [3]]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?