在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< TSource> (IEnumerable< TSource>秒)
Seq.concat = SelectMany< IEnumerable< TSource> ;, TResult> ;(s => s)
Seq.distinct_by = GroupBy(keySelector).Select( g => g.First())
Seq.exists =任何< TSource>( Func< TSource,bool>谓词)
Seq.mapi = Select< TSource,TResult>( Func< TSource,Int32,TResult>选择器)
Seq.fold = Aggregate< TSource,TAccumulate> ;(TAccumulate seed,Func< TAccumulate,TSource,TAccumulate> func)
List.partition
的定义如下:
将集合分为两个集合,其中包含给定谓词返回
true
和false
分别
我们可以使用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保留错误值。
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屋!