加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#中的Monadic理解语法

发布时间:2020-12-16 01:58:04 所属栏目:百科 来源:网络整理
导读:几天前我一直在# haskell IRC房间里闲逛,有人提到C#具有进行monadic理解的语法.这是什么意思? 如果我理解正确的话,monadic理解只是对绑定操作进行排序的一种方式,这听起来像是一种符号?那是对的吗? 问题是我在C#中没有看到这个.据我所知IEnumerable T是一
几天前我一直在# haskell IRC房间里闲逛,有人提到C#具有进行monadic理解的语法.这是什么意思?

如果我理解正确的话,monadic理解只是对绑定操作进行排序的一种方式,这听起来像是一种符号?那是对的吗?

问题是我在C#中没有看到这个.据我所知IEnumerable< T>是一个monad,其中SelectMany是它的绑定函数,因为它的签名是A – > IEnumerable的<乙取代.只需一点想象力,我们就可以做到

from x in xs
from y in ys

这转化为(我不是100%肯定在这里)

xs.SelectMany(x => ys.Select(y => y),(x,y) => ...)

但即使这是真的,我们将LINQ视为monad理解语法,它仍然只适用于IEnumerable< T>.我们在C#中有其他monad,比如Task< T>,但是我们如何在那些上使用LINQ?

这个问题中的许多假设可能是完全错误的,因为我仍然试图掌握一些monad神奇的东西.如果我错了请纠正我:)

解决方法

LINQ查询语法只是语法糖,并且对IEnumerable<>一无所知,这就是为什么你可以将它用于其他事情.

如果检查C# language specification,它将描述如何在7.16.2节中转换LINQ的查询表达式

The C# language does not specify the execution semantics of query expressions. Rather,query expressions are translated into invocations of methods that adhere to the query expression pattern (§7.16.3). Specifically,query expressions are translated into invocations of methods named Where,Select,SelectMany,Join,GroupJoin,OrderBy,OrderByDescending,ThenBy,ThenByDescending,GroupBy,and Cast.These methods are expected to have particular signatures and result types,as described in §7.16.3. These methods can be instance methods of the object being queried or extension methods that are external to the object,and they implement the actual execution of the query.

您的具体示例描述为

A query expression with a second from clause followed by a select clause

from x1 in e1
from x2 in e2
select v

is translated into

( e1 ) . SelectMany( x1 => e2,( x1,x2 ) => v )

因此,使用示例中的变量名称,任何具有方法Treturned SelectMany(Func< Tx,Tys>,Func< Tx,Ty,Treturned>)的xs都可以在类似的语句中使用

Treturned returned =
    from x in xs
    from y in ys
    select r;

这将完全编译时

Treturned returned = xs.SelectMany(x => ys,y) => r);

是的,这是xs上存在这种方法的任何时候. SelectMany存在于IEnumerable<>的事实并不妨碍我们为其他类型配备具有相同名称的方法或扩展方法.

C#可以从它知道xs是什么的事实推断lambdas的类型,并且从中可以查找类型到xs的SelectMany的参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读