如何在 Rx 中进行模式匹配。 Where 和 Select 在单个运算符中?
How to do pattern matching in Rx. Where and Select in a single operator?
假设我有这种类型:
type T = int option
以及该类型的可观察对象:
let o : IObservable<T> = // create the observable
我正在寻找一种更好的表达方式:
o.Where(function | None -> false | Some t -> true)
.Select(function | Some t -> t)
An observable that only propagates the Some
case.
有几件事我不喜欢。
- 我正在使用 2 个运算符
- 我进行了两次模式匹配
- 第二个模式匹配并不详尽(使 visual studio 显示警告并感觉很奇怪)
- 代码太多。每次我需要模式匹配时,模式都会重复。
感谢@Lee,我想出了一个很好的解决方案。
o.SelectMany(function | None -> Observable.Empty() | Some t -> Observable.Return t)
这适用于任何联合类型,而不仅仅是 Option。
你不能用Observable.choose吗?像这样:
let o1 : IObservable<int option> = // ...
let o2 = Observable.choose id o1
如果您的类型不是一个选项,请说:
type TwoSubcases<'a,'b> = | Case1 of 'a | Case2 of 'b
和部分活动模式:
let (|SecondCase|_|) = function
| Case1 _ -> None
| Case2 b -> Some b
那么你可以这样做:
let o1 : IObservable<TwoSubcases<int, float>> = // ...
let o2 : IObservable<float> = Observable.choose (|SecondCase|_|) o1
假设我有这种类型:
type T = int option
以及该类型的可观察对象:
let o : IObservable<T> = // create the observable
我正在寻找一种更好的表达方式:
o.Where(function | None -> false | Some t -> true)
.Select(function | Some t -> t)
An observable that only propagates the
Some
case.
有几件事我不喜欢。
- 我正在使用 2 个运算符
- 我进行了两次模式匹配
- 第二个模式匹配并不详尽(使 visual studio 显示警告并感觉很奇怪)
- 代码太多。每次我需要模式匹配时,模式都会重复。
感谢@Lee,我想出了一个很好的解决方案。
o.SelectMany(function | None -> Observable.Empty() | Some t -> Observable.Return t)
这适用于任何联合类型,而不仅仅是 Option。
你不能用Observable.choose吗?像这样:
let o1 : IObservable<int option> = // ...
let o2 = Observable.choose id o1
如果您的类型不是一个选项,请说:
type TwoSubcases<'a,'b> = | Case1 of 'a | Case2 of 'b
和部分活动模式:
let (|SecondCase|_|) = function
| Case1 _ -> None
| Case2 b -> Some b
那么你可以这样做:
let o1 : IObservable<TwoSubcases<int, float>> = // ...
let o2 : IObservable<float> = Observable.choose (|SecondCase|_|) o1