Mik*_*ike 9 c# monads ienumerable
我有一个普遍的问题和一个更具体的案例问题.
一般来说,如何组合不同的monad?monad运算符的某些组合是否允许轻松组合?或者是否必须编写特殊方法来组合每对可能的monad?
作为一个具体的例子,我写了一个Maybe monad.如何使用IEnumerable<IMaybe<T>>?除了手动挖掘LINQ扩展中的Maybe monad(例如:if(maybe.HasValue)...... select子句中)之外,是否有一种"monadic"方式将两者与各自的Bind等monad操作相结合?
否则,如果我必须编写特定的组合方法,这是正确的方法吗?
public static IEnumerable<B> SelectMany<A, B>(this IEnumerable<A> sequence, Func<A, IMaybe<B>> func)
{
return from item in sequence
let result = func(item)
where result.HasValue
select result.Value;
}
public static IEnumerable<C> SelectMany<A, B, C>(this IEnumerable<A> sequence, Func<A, IMaybe<B>> func, Func<A, B, C> selector)
{
return from item in sequence
let value = item
let maybe = func(item)
where maybe.HasValue
select selector(value, maybe.Value);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
760 次 |
| 最近记录: |