Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this C# code get done in functional languages (F#? Haskel?)

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;
});
like image 333
Aaron Anodide Avatar asked Jul 04 '11 20:07

Aaron Anodide


People also ask

How does C language work?

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.

How does a do while loop work in C?

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.

What does &= mean in C?

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.


1 Answers

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.

like image 74
hammar Avatar answered Sep 28 '22 16:09

hammar