Created
August 28, 2012 01:06
-
-
Save jsakamoto/3494035 to your computer and use it in GitHub Desktop.
C# with LINQ での FirstOrDefault と ?? 演算子みたいなことを F# で書いてみる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C# の ?? 演算子と同様の用途・目的で、|?? というユーザー定義の記号演算子をあらかじめ定義しておく。 | |
// ただし null かどうかではなく、Option型の引数をとって Some(a) なら a を、 | |
// None であれば第2引数に指定された既定値を返す仕組み。 | |
let (|??) opt def = | |
match opt with | |
|Some(a) -> a | |
|None -> def | |
// LINQ の FirstOrDefault に近いのは、Seq.tryFind。 | |
// Seq.tryFind は、集合の中から predicate で該当するものがあれば Some(a)、 | |
// 見つからなければ None が返る。 | |
// さらに先に定義した |?? 演算子をくぐせば、変数 exact には必ず何かしらの値が束縛される。 | |
let exact = collection |> Seq.tryFind predicate |?? defaultValue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment