Ruby中的LINQ特性

本文关键字:特性 LINQ 中的 Ruby | 更新日期: 2023-09-27 18:14:14

我想用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#中它缺乏一点…)

我相信ruby有这些特性,我很有兴趣看看等效的代码是什么样子的。

Ruby中的LINQ特性

我把你的代码翻译成ruby(并重写了一点):

  # candidate - Enumerable of Enumerable; world - Enumerable; &block - comparer of two sets.
  def topology? candidate, world, &block
    require 'set'
    # you can pass block to this method or if no block passed it will use set comparison
    comparer = block || lambda { |ary1,ary2| ary1.to_set.eql?(ary2.to_set) }
    # create lambda-function to find a specified set in candidate (to reuse code)
    candidate_include = lambda { |to_find| candidate.find {|item| comparer.(item, to_find) } }
    return false if( !candidate_include.( []) || !candidate_include.( world) )
    pairs = candidate.to_a.repeated_permutation(2)
    pairs.all? do |x,y| x_set = x.to_set; y_set = y.to_set
        candidate_include.(x_set & y_set) && # or x_set.intersection y_set
        candidate_include.(x_set | y_set) # or x_set.union y_set
    end
  end

希望能有所帮助