一个很好的例子是埃拉托色尼筛。
我和一位同事用 C# 和 F# 编写了类似的筛子。 C# 版本的性能几乎比我同事编写的功能版本慢 10 倍。
C# 版本中可能有一些效率低下的地方可以清理,但 F# 版本明显更快。
这类问题适合用函数式语言编写..
希望这会有所帮助。
编辑 -
这是使用与 F# 的 List.Partition 类似功能的 C# 示例之一。我将继续寻找 F# 示例。我有数百个可能参与的项目,只需对我所有的东西进行分类即可找到它(我保存了我曾经尝试过的所有东西,所以这可能很耗时..哈哈)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListPartitionTest
{
public static class IEnumerableExtensions
{
public static KeyValuePair<IEnumerable<T>, IEnumerable<T>> Partition<T>(this IEnumerable<T> items, Func<T, bool> f)
{
return items.Aggregate(
new KeyValuePair<IEnumerable<T>, IEnumerable<T>>(Enumerable.Empty<T>(), Enumerable.Empty<T>()),
(acc, i) =>
{
if (f(i))
{
return new KeyValuePair<IEnumerable<T>, IEnumerable<T>>(acc.Key.Concat(new[] { i }), acc.Value);
}
else
{
return new KeyValuePair<IEnumerable<T>, IEnumerable<T>>(acc.Key, acc.Value.Concat(new[] { i }));
}
});
}
}
class PrimeNumbers
{
public int Floor { get; private set; }
public int Ceiling { get; private set; }
private IEnumerable<int> _sieve;
public PrimeNumbers(int floor, int ceiling)
{
Floor = floor;
Ceiling = ceiling;
}
public List<int> Go()
{
_sieve = Enumerable.Range(Floor, (Ceiling - Floor) + 1).ToList();
for (int i = (Floor < 2) ? 2 : Floor; i <= Math.Sqrt(Ceiling); i++)
{
_sieve = _sieve.Where(x => (x % i != 0 && x != i));
foreach (int x in _sieve)
{
Console.Write("{0}, ", x);
}
Console.WriteLine();
}
return _sieve.ToList();
}
}
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
int floor = 1;
int ceiling = 10;
s.Start();
PrimeNumbers p = new PrimeNumbers(floor, ceiling);
p.Go();
//foreach (int i in p.Go()) Console.Write("{0} ", i);
s.Stop();
Console.WriteLine("\n{0} to {1} completed in {2}", floor, ceiling, s.Elapsed.TotalMilliseconds);
Console.ReadLine();
}
}
}