在 C# 中为 IEnumerable 实现的 F# Seq 模块? [英] F# Seq module implemented in C# for IEnumerable?
问题描述
F# 有一堆标准序列运算符,我从使用 Mathematica 的经验中逐渐了解和喜爱.F#现在引起了我的广泛关注,当它正式发布时,我打算经常使用它.
F# has a bunch of standard sequence operators I have come to know and love from my experience with Mathematica. F# is getting lots of my attention now, and when it is in general release, I intend to use it frequently.
现在,由于 F# 尚未正式发布,我无法在生产代码中真正使用它.LINQ 使用类似 SQL 的名称实现了其中一些运算符(例如,select"是map",where"是filter"),但我找不到fold"、iter"或partition"的实现.
Right now, since F# isn't yet in general release, I can't really use it in production code. LINQ implements some of these operators using SQL-like names (e.g. 'select' is 'map', and 'where' is 'filter'), but I can find no implementation of 'fold', 'iter' or 'partition'.
有没有人见过标准序列运算符的任何 C# 实现?这是应该有人写的吗?
Has anyone seen any C# implementation of standard sequence operators? Is this something someone should write?
推荐答案
如果您仔细观察,许多 Seq 操作都有 LINQ 等效项或可以轻松派生.只是俯视 列表...
If you look carefully, many Seq operations have a LINQ equivalent or can be easily derived. Just looking down the list...
Seq.append = Concat
(IEnumerable second)
Seq.concat = SelectMany
Seq.distinct_by = GroupBy(keySelector).Select(g => g.First())
Seq.exists = Any
Seq.mapi = Select
Seq.fold = Aggregate
List.partition
定义如下:
将集合拆分为两个集合,分别包含给定谓词返回true
和false
的元素
Split the collection into two collections, containing the elements for which the given predicate returns
true
andfalse
respectively
我们可以使用 GroupBy 和一个二元数组作为穷人的元组来实现:
Which we can implement using GroupBy and a two-element array as a poor-man's tuple:
public static IEnumerable<TSource>[] Partition<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
return source.GroupBy(predicate).OrderByDescending(g => g.Key).ToArray();
}
元素 0 保存真实值;1 持有假值.GroupBy 本质上是类固醇的分区.
Element 0 holds the true values; 1 holds the false values. GroupBy is essentially Partition on steroids.
最后,Seq.iter
和 Seq.iteri
很容易映射到 foreach:
And finally, Seq.iter
and Seq.iteri
map easily to foreach:
public static void Iter<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
{
foreach (var item in source)
action(item);
}
public static void IterI<TSource>(this IEnumerable<TSource> source, Action<Int32, TSource> action)
{
int i = 0;
foreach (var item in source)
action(i++, item);
}
这篇关于在 C# 中为 IEnumerable 实现的 F# Seq 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!