LoginSignup
0
0

More than 5 years have passed since last update.

【F#】Seq.pairwise

Last updated at Posted at 2014-03-30

F# の Seq.pairwise は良いですね。
pairwise は zip を使って次のように実装することもできますが、

let pairwiseByZip x = Seq.zip x (Seq.skip 1 x)

これだと、シーケンスによっては扱いが面倒になる場合があります。たとえば、ファイルを読み込んでシーケンスにするような場合を考えます:

let lines =
    seq {
        use r = new StreamReader(path)
        printfn "read: %s" path
        while r.Peek() >= 0 do
            yield r.ReadLine()
    }

printfn "%d" (lines |> pairwiseByZip |> Seq.length)

これに対し、10行のファイル sample.txt のパスをpathとして与えて実行すると、次のようになりました。

read: sample.txt
read: sample.txt
9

2回ファイルを読み込んでいました。ここで、pairwiseByZipをSeq.pairwiseに変える:

printfn "%d" (lines |> Seq.pairwise |> Seq.length)

と結果は

read: sample.txt
9

となり、ファイルの読み込みは1回です。

シーケンスを扱う場合はこういうことにも気をつけないと(自戒)。

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