Ruby 中的 LINQ 功能
我想用 Ruby 编写一段代码,其行为类似于 C# 代码。
它接收候选拓扑集和世界集,并测试候选拓扑是否是关于世界的拓扑。
在使用 LINQ 功能的 C# 中,它看起来像这样:
public static bool IsTopology<T>(IEnumerable<IEnumerable<T>> candidate, IEnumerable<T> world)
{
IEqualityComparer<IEnumerable<T>> setComparer =
new SetComparer<T>();
if (!candidate.Contains(Enumerable.Empty<T>(), setComparer) ||
!candidate.Contains(world, setComparer))
{
return false;
}
var pairs =
from x in candidate
from y in candidate
select new {x,y};
return pairs.All(pair => candidate.Contains(pair.x.Union(pair.y), setComparer) &&
candidate.Contains(pair.x.Intersect(pair.y), setComparer));
}
public class SetComparer<T> : IEqualityComparer<IEnumerable<T>>
{
public bool Equals (IEnumerable<T> x, IEnumerable<T> y)
{
return new HashSet<T>(x).SetEquals(y);
}
public int GetHashCode (IEnumerable<T> obj)
{
return 0;
}
}
我正在寻找的功能如下:
将相等比较器插入方法的能力
一种能力使用嵌套映射(和匿名类型)
将数组作为集合进行比较的能力(不是很重要,在 C# 中它缺少一点...)< /p>
我相信 ruby 具有这些功能,并且非常有兴趣了解等效代码的外观。
I would like to write a code in Ruby that behaves like this C# code.
It receives a candidate topology set and a world set, and tests if the candidate topology is a topology in respect to the world.
In C# using LINQ features it looks like this:
public static bool IsTopology<T>(IEnumerable<IEnumerable<T>> candidate, IEnumerable<T> world)
{
IEqualityComparer<IEnumerable<T>> setComparer =
new SetComparer<T>();
if (!candidate.Contains(Enumerable.Empty<T>(), setComparer) ||
!candidate.Contains(world, setComparer))
{
return false;
}
var pairs =
from x in candidate
from y in candidate
select new {x,y};
return pairs.All(pair => candidate.Contains(pair.x.Union(pair.y), setComparer) &&
candidate.Contains(pair.x.Intersect(pair.y), setComparer));
}
public class SetComparer<T> : IEqualityComparer<IEnumerable<T>>
{
public bool Equals (IEnumerable<T> x, IEnumerable<T> y)
{
return new HashSet<T>(x).SetEquals(y);
}
public int GetHashCode (IEnumerable<T> obj)
{
return 0;
}
}
The features I am looking for are the following:
An ability to plug an equality comparer to methods
An ability to use nested maps (and anonymous types)
An ability to compare arrays as sets (not very important, in C# it lacks a bit...)
I believe that ruby has the features and am very interested to see how the equivalent code would look like.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将你的代码翻译成 ruby(并重写了一点):
希望这有帮助
I translated your code to ruby (and rewritten it a bit):
Hope this helps