这个C#代码是如何在函数式语言中完成的(F#?Haskel?)

Aar*_*ide 5 c# functional-programming c#-to-f#

我怎么能用F#或Haskel或类似的函数式语言编写这个C#代码?

var lines = File.ReadAllLines(@"\\ad1\\Users\aanodide\Desktop\APIUserGuide.txt");

// XSDs are lines 375-471
var slice = lines.Skip(374).Take(471-375+1);

var kvp = new List<KeyValuePair<string, List<string>>>(); 
slice.Aggregate(kvp, (seed, line) => 
{
    if(line.StartsWith("https"))
        kvp.Last().Value.Add(line);
    else
        kvp.Add(
            new KeyValuePair<string,List<string>>(
                line, new List<string>()
            )
        );
    }
    return kvp;
});
Run Code Online (Sandbox Code Playgroud)

ham*_*mar 6

所以,如果我正确读取你的代码,你的输入看起来像这样:

[...]
Foo
https://example1.com
https://example2.com
Bar
https://example3.com
Baz
Xyzzy
https://example4.com
[...]
Run Code Online (Sandbox Code Playgroud)

从这里,您希望标题与它们下面的URL分组.这是一个Haskell程序,它执行此操作:

import Data.List (isPrefixOf)

groupUrls :: [String] -> [(String, [String])]
groupUrls [] = []
groupUrls (header:others) = (header, urls) : groupUrls remaining
  where (urls, remaining) = span (isPrefixOf "https") others

main = do
    input <- readFile "\\\\ad1\\\\Users\\aanodide\\Desktop\\APIUserGuide.txt"
    let slice = take (471 - 375 + 1) $ drop 374 $ lines input
    let kvp = groupUrls slice
    print kvp
Run Code Online (Sandbox Code Playgroud)

输出:

[("Foo",["https://example1.com","https://example2.com"]),("Bar", ["https://example3.com"]),("Baz",[]),("Xyzzy",["https://example4.com"])]
Run Code Online (Sandbox Code Playgroud)

这里感兴趣的关键功能是span,这里使用连续的行开始"https"并将它们与剩余的行一起返回,然后以递归的方式处理它们.