给定:
open System.Linq
这是一个可接受的表达:
[2; 3; 4].SelectMany(fun n -> { 1..n })
然而,这并不是:
[2; 3; 4].SelectMany(fun n -> [ 1..n ])
错误信息显示:
int -> int list
is not compatible with type
int -> System.Collections.Generic.IEnumerable<'a>
F#拒绝这个表达式,因为函数返回了一个int list
。
考虑这个类似的C#程序:
using System;
using System.Collections.Generic;
using System.Linq;
namespace SelectManyCs
{
class Program
{
static List<int> Iota(int n)
{
var ls = new List<int>();
for (var i = 0; i < n; i++) ls.Add(i);
return ls;
}
static void Main(string[] args)
{
var seq = new List<int>() { 2, 3, 4 };
foreach (var elt in seq.SelectMany(Iota))
Console.WriteLine(elt);
}
}
}
Iota
返回一个 List<int>
,并将其传递给 SelectMany
在 C# 中是可接受的。
F# 的行为是设计如此还是 bug?如果是设计如此,为什么类似的操作在 C# 中可以工作?
System.Collections.Generic.List<T>
和Microsoft.FSharp.Collections.List<T>
。 - Martin Liversage