/
Main.cs
98 lines (80 loc) · 2.66 KB
/
Main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Inspired by https://gist.github.com/louthy/524fbe8965d3a2aae1b576cdd8e971e4
using FreeAwait;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
await Test("rhyme.txt");
async Task Test(string path)
{
await MonadicIOComputation(path, $"live-{path}").Use(new LiveInterpreter());
await MonadicIOComputation(path, $"async-{path}").Use(new LiveInterpreterAsync());
await MonadicIOComputation(path, $"mock-{path}").Use(new MockInterpreter());
}
async IStep<Void> MonadicIOComputation(string inPath, string outPath)
{
var lines = (await new ReadAllLines(inPath)).ToList();
await new Log($"There are {lines.Count} lines in {inPath}");
await new Log("Prepending line numbers");
var newLines = Enumerable.Range(1, int.MaxValue).Zip(lines).Select(item => $"{item.First} {item.Second}");
await new WriteAllLines(outPath, newLines);
await new Log($"Lines prepended and {outPath} saved successfully");
return default;
}
struct Void { }
record ReadAllLines(string Path): IStep<ReadAllLines, IEnumerable<string>>;
record WriteAllLines(string Path, IEnumerable<string> Output): IStep<WriteAllLines, Void>;
record Log(string Output): IStep<Log, Void>;
interface IInterpreter:
IRun<ReadAllLines, IEnumerable<string>>,
IRun<WriteAllLines, Void>,
IRun<Log, Void>
{
}
interface IInterpreterAsync:
IRunAsync<ReadAllLines, IEnumerable<string>>,
IRunAsync<WriteAllLines, Void>,
IRunAsync<Log, Void>
{ }
class LiveInterpreter : IInterpreter
{
public IEnumerable<string> Run(ReadAllLines command) =>
File.ReadAllLines(command.Path);
public Void Run(WriteAllLines command)
{
File.WriteAllLines(command.Path, command.Output);
return default;
}
public Void Run(Log command)
{
Console.WriteLine(command.Output);
return default;
}
}
class LiveInterpreterAsync : IInterpreterAsync
{
public async Task<IEnumerable<string>> RunAsync(ReadAllLines command) =>
await File.ReadAllLinesAsync(command.Path);
public async Task<Void> RunAsync(WriteAllLines command)
{
await File.WriteAllLinesAsync(command.Path, command.Output);
return default;
}
public Task<Void> RunAsync(Log command)
{
Console.WriteLine(command.Output);
return Task.FromResult<Void>(default);
}
}
class MockInterpreter : IInterpreter
{
public IEnumerable<string> Run(ReadAllLines command) =>
new[] { "Hello", "World" }.AsEnumerable();
public Void Run(WriteAllLines _) => default;
public Void Run(Log command)
{
Console.WriteLine(command.Output);
return default;
}
}