在F#中取每个子序列?

时间:2014-11-21 20:36:35

标签: c# f# c#-to-f#

我编写了这个C#代码来获取一组单词的每个子序列。

    static IEnumerable<IEnumerable<string>> Subsequences(IEnumerable<string> words)
    {
        var arr = words as string[] ?? words.ToArray();
        int len = arr.Count();
        for (int i = 1; i < len; i++)
            for (int j = 0; i + j <= len; j++)
                yield return arr.Skip(j).Take(i);
    }

你会如何用F#写这个?

1 个答案:

答案 0 :(得分:2)

这是一个具有相同逻辑的翻译:

let subsequences words =
    seq {
        let len = Array.length words
        for i = 1 to len - 1 do
            for j = 0 to len - i do
                yield words.[j..j+i-1]
    }