How could I write this C# code in F# or Haskel, or a similar functional language?
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;
});
C is what's referred to as a compiled language, meaning you have to use a compiler to turn the code into an executable file before you can run it. The code is written into one or more text files, which you can open, read and edit in any text editor, such as Notepad in Windows, TextEdit on a Mac, and gedit in Linux.
A do while loop is similar to while loop with one exception that it executes the statements inside the body of do-while before checking the condition. On the other hand in the while loop, first the condition is checked and then the statements in while loop are executed.
It means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form.
So, if I read your code correctly, your input looks something like this:
[...]
Foo
https://example1.com
https://example2.com
Bar
https://example3.com
Baz
Xyzzy
https://example4.com
[...]
From this, you want the headers grouped with the URLs below them. Here's a Haskell program that does this:
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
Output:
[("Foo",["https://example1.com","https://example2.com"]),("Bar", ["https://example3.com"]),("Baz",[]),("Xyzzy",["https://example4.com"])]
The key function of interest here is span
, which is used here to take the consecutive lines starting with "https"
and return them together with the remaining lines, which are then dealt with recursively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With