-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
executable file
·642 lines (544 loc) · 19.8 KB
/
Program.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ConsoleApplication1
{
public class SkadeChat
{
private static IStep[] bil =
{
q("I Alka håndterer vi over 30.000 bilskader hvert år. Vil du have nogle generelle råd?")
.OnYes("Jeg har ingen råd, men nice try"),
q("Inden vi starter skal vi lige tjekke de oplysninger vi har om dig"),
If("Vi kender bilen", s => !s.s.ContainsKey("carmodel"),
q("Vi har desværre ingen oplysninger om din bil."),
q("Indtast dine biloplysninger", "carmodel"),
q("Vi har nu registreret at din bil er en {carmodel}"))
.Else(q("Er din bil en {carmodel}?")
.OnNo(
q("Så er der noget galt med vores oplysninger. Indtast din bil", "carmodel"),
q("Vi har nu registreret at din bil er en {carmodel}"))),
q("Hvor og hvornår skete skaden?", "whereandwhen"),
q("Hvilke dele af bilen blev beskadiget?", "damage")
.On("fronten")
.On("bagsmækken")
.On("lygterne")
.On("venstre fordør"),
q("Hvor mange var I i bilen?", "passengers").On("1").On("2").On("3").On("4"),
q("Kære {name}. Vi har registreret at du {whereandwhen} har haft en skade på din {carmodel}, hvor I var {passengers} i bilen og {damage} blev beskadiget."),
q("Helmers autoværksted ringer til dig i morgen, så I kan aftale en tid")
};
private static IStep[] hest =
{
q("Fortæl mig hvad der skete med din hest?", "accident").On("rideulykke").On("anden ulykke"),
q("Skete din {accident} fordi du var fuld?").OnNo("Så dækker vi måske").OnYes("Så dækker vi ikke")
};
private static IStep[] f2 =
{
q("Hvad hedder du?", "name"),
q("Hej {name}, det er aldrig rart når man er ude for et uheld."),
q("Hvad er gået i stykker?")
.On("Bil", bil)
.On("Hest", hest),
q("Hav en fortsat god dag")
};
private static IStep[] questions =
{
q("Er du programmør?").OnNo(q("Ok, farvel")).OnYes(
q("Sejt, så har jeg nogle spørgsmål til dig"),
q("Hvad er dit yndlingsprogrammeringssprog?", "favlang"),
If("fav is f#", s => s.Get("favlang").Equals("f#"), q("Du er en hård banan")).Else(q("Du virker ellers som VB-typen")),
q("Coding rocks, skriv noget sej {favlang}-kode"))
};
public static void Main(string[] args)
{
//var state = new State();
////state.Set("carmodel", "Ford Mustang 1978");
//var hist = new List<string>();// {"Poul", "Bil", "Ja", "Nej", "Ford Focus", "fredag morgen ved Bilka", "fronten", "2" };
//RunChat(questions, hist, state);
Console.WriteLine(RenderCode2Flow(questions.ToList(), new State()));
}
private static void RunChat(IStep[] flow, List<string> hist, State origState)
{
var newHist = new List<string>();
string q = null;
var res = Result.Ok(new List<Statement>());
do
{
var state = new State(origState);
Console.WriteLine("========================");
res = Exec(flow.ToList(), state, hist.AddToList(q));
if (res.IsFailure)
{
Console.WriteLine(res.Error);
q = null;
continue;
}
foreach (var statement in res.Value)
{
if (statement.Speaker == Statement.Chatter.Person)
{
newHist.Add(statement.Chat);
}
Console.WriteLine(statement.Speaker + ": " + statement.Chat);
}
q = res.Value[res.Value.Count - 1].IsBreaking ? Console.ReadLine() : null;
hist = newHist;
newHist = new List<String>();
} while (res.IsFailure || res.Value[res.Value.Count - 1].IsBreaking);
}
private static string RenderCode2Flow(List<IStep> flow, State state)
{
var res = "";
foreach (var s in flow)
{
var r = "";
var q = s as Question;
var ibs = s as IBranchStep;
var ils = s as ILabelStep;
var postLabel = "";
if (q?.Key != null)
{
state.Set(q.Key, "'" + q.Key + "'");
postLabel = " (" + q.Key + ")";
}
if (ibs != null)
{
var label = ibs.Tag.StringFormat(state.s);
r = "switch (" + label + postLabel + ") {" + Environment.NewLine;
foreach (var key in ibs.GetPreds().Keys)
{
r += "case " + key + ":" + Environment.NewLine;
r += RenderCode2Flow(ibs.GetRoutes()[key].ToList(), state);
r += "break;" + Environment.NewLine;
}
r += "}" + Environment.NewLine;
}
else
{
var label = ils?.Label.StringFormat(state.s);
r += label + postLabel + ";" + Environment.NewLine;
}
res += r;
}
return res;
}
static Result<List<Statement>> Exec(List<IStep> flow, State st, List<string> hist)
{
List<IStep> lines = RunToNextBreak(flow, st);
List<Statement> res = new List<Statement>();
foreach (var s in hist)
{
var q = lines.Last();
st.Set((q as Question)?.Key, s);
var a = HandleAnswer(q as IBranchStep, s, st);
if (a.IsFailure)
{
return Result.Fail<List<Statement>>(a.Error);
}
flow.InsertRange(0, a.Value);
res.AddRange(StepsToStatements(lines, st));
res.Add(Statement.HumanSays(s));
lines = RunToNextBreak(flow, st);
}
res.AddRange(StepsToStatements(lines, st));
return Result.Ok(res);
}
static List<Statement> StepsToStatements(List<IStep> steps, State st)
{
var res = new List<Statement>();
foreach (var ss in steps)
{
res.Add(Statement.RobotSays(ss as ILabelStep, st));
}
return res;
}
private static Result<List<IStep>> HandleAnswer(IBranchStep q, string answer, State st)
{
var res = Result.Ok(new List<IStep>());
if (q == null || q.GetRoutes().Count == 0)
{
return res;
}
return FindRouteToPred(q, answer, st);
}
private static Result<List<IStep>> FindRouteToPred(IBranchStep q, string answer, State st)
{
foreach (var pred in q.GetPreds())
{
if (pred.Value(st, answer))
{
return Result.Ok(q.GetRoutes()[pred.Key].ToList());
}
}
return Result.Fail<List<IStep>>($"Du kan ikke svare '{answer}' på dette spørgsmål");
}
static List<IStep> RunToNextBreak(List<IStep> flow, State st)
{
var res = new List<IStep>();
IStep step = null;
while (flow.Count > 0 && !(step is Question))
{
step = flow.TakeNext();
if (step is BranchOnState)
{
flow.InsertRange(0, FindRouteToPred(step as IBranchStep, "", st).Value);
}
else
{
res.Add(step);
}
}
return res;
}
private static ILabelStep q(string q)
{
return new Line(q);
}
private static Question q(string q, string id)
{
return new Question(q, id);
}
private static BranchOnState If(string tag, Predicate<State> p, params IStep[] qs)
{
return new BranchOnState(tag, p, qs);
}
}
public class Statement
{
public enum Chatter { Robot, Person };
public readonly Chatter Speaker;
public readonly string Chat;
public readonly bool IsBreaking;
public List<string> Alternatives;
private Statement(string q, Chatter chatter, bool isBreaking)
{
Speaker = chatter;
Chat = q;
Alternatives = new List<string>();
this.IsBreaking = isBreaking;
}
public static Statement RobotSays(ILabelStep q, State st)
{
var s = q.Label.StringFormat(st.s);
if (q is IBreakingStep)
{
var qu = q as IBranchStep;
if (qu is ILabelStep && qu.GetRoutes().Count > 0)
{
s += " (" + String.Join(", ", qu.GetPreds().Keys) + ")";
}
}
return new Statement(s, Chatter.Robot, q is IBreakingStep);
}
public static Statement HumanSays(string q)
{
return new Statement(q, Chatter.Person, false);
}
}
public interface IStep
{
}
public interface IBreakingStep : IStep
{
}
public interface ILabelStep : IStep
{
string Label { get; }
}
public interface IBranchStep : IStep
{
string Tag { get; }
Dictionary<string, IStep[]> GetRoutes();
Dictionary<string, Func<State, object, bool>> GetPreds();
}
public class Line : ILabelStep
{
public string Label { get; }
public Line(string t)
{
this.Label = t;
}
}
public class BranchOnState : IBranchStep
{
private readonly Dictionary<string, IStep[]> routes = new Dictionary<string, IStep[]>();
private readonly Dictionary<string, Func<State, object, bool>> preds = new Dictionary<string, Func<State, object, bool>>();
public string Tag { get; }
public BranchOnState(string tag, Predicate<State> p, params IStep[] qs)
{
Tag = tag;
preds["if"] = (s, e) => p(s);
preds["else"] = (s, e) => !p(s);
routes["if"] = qs;
routes["else"] = new IStep[0];
}
public BranchOnState Else(params IStep[] qs)
{
routes["else"] = qs;
return this;
}
public Dictionary<string, IStep[]> GetRoutes()
{
return routes;
}
public Dictionary<string, Func<State, object, bool>> GetPreds()
{
return preds;
}
}
public class Question : Line, IBreakingStep
{
public readonly string Key;
public Question(string t, string key) : base(t)
{
this.Key = key;
}
}
public class BranchQuestion : Question, IBranchStep
{
public string Tag { get; }
private readonly Dictionary<string, IStep[]> routes = new Dictionary<string, IStep[]>();
private readonly Dictionary<string, Func<State, object, bool>> preds = new Dictionary<string, Func<State, object, bool>>();
public BranchQuestion(string t, string key) : base(t, key)
{
Tag = t;
}
public BranchQuestion RegisterRoute(string key, IStep[] q)
{
routes[key] = q;
return this;
}
public BranchQuestion RegisterPred(string key, Predicate<Object> p)
{
preds[key] = (s, e) => p(e);
return this;
}
public Dictionary<string, IStep[]> GetRoutes()
{
return routes;
}
public Dictionary<string, Func<State, object, bool>> GetPreds()
{
return preds;
}
}
public static class QuestionExtensions
{
public static List<string> AddToList(this List<string> hist, string a)
{
List<string> s = new List<string>(hist);
if (a != null)
{
s.Add(a);
}
return s;
}
public static IStep TakeNext(this List<IStep> flow)
{
var res = flow[0];
flow.RemoveAt(0);
return res;
}
public static Question OnYes(this ILabelStep s, params IStep[] qs)
{
var res = s.ToQuestion().On("Ja", e => "Ja".Equals(e), qs);
return res.GetRoutes().ContainsKey("Nej") ? res : res.On("Nej", e => !"Ja".Equals(e));
}
public static Question OnNo(this ILabelStep s, params IStep[] qs)
{
var res = s.ToQuestion().On("Nej", e => !"Ja".Equals(e), qs);
return res.GetRoutes().ContainsKey("Ja") ? res : res.On("Ja", e => "Ja".Equals(e));
}
public static Question OnYes(this ILabelStep q, string s)
{
return OnYes(q, new Line(s));
}
public static Question OnNo(this ILabelStep q, string s)
{
return OnNo(q, new Line(s));
}
public static Question ToQuestion(this ILabelStep st)
{
return st as Question ?? new Question(st.Label, null);
}
public static BranchQuestion ToBranchQuestion(this Question st)
{
return st as BranchQuestion ?? new BranchQuestion(st.Label, st.Key);
}
public static BranchQuestion On(this ILabelStep q, string key, Predicate<object> p, params IStep[] qs)
{
var qq = q.ToQuestion().ToBranchQuestion();
return qq.RegisterRoute(key, qs).RegisterPred(key, p);
}
public static BranchQuestion On(this ILabelStep q, string key, params IStep[] qs)
{
var qq = ToQuestion(q);
return On(qq, key, s => s.Equals(key), qs);
}
public static string StringFormat(this string format, IDictionary<string, string> values)
{
foreach (var p in values)
format = format.Replace("{" + p.Key + "}", p.Value);
return format;
}
}
public class State
{
public Dictionary<string, string> s;
public State(State origState)
{
s = new Dictionary<string, string>(origState.s);
}
public State()
{
s = new Dictionary<string, string>();
}
public string Get(string key)
{
return s.ContainsKey(key) ? s[key] : "";
}
public State Set(string key, string val)
{
if (key != null)
{
s[key] = val;
}
return this;
}
}
internal sealed class ResultCommonLogic
{
public bool IsFailure { get; }
public bool IsSuccess => !IsFailure;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly string _error;
public string Error
{
[DebuggerStepThrough]
get
{
if (IsSuccess)
throw new InvalidOperationException("There is no error message for success.");
return _error;
}
}
[DebuggerStepThrough]
public ResultCommonLogic(bool isFailure, string error)
{
if (isFailure)
{
if (string.IsNullOrEmpty(error))
throw new ArgumentNullException(nameof(error), "There must be error message for failure.");
}
else
{
if (error != null)
throw new ArgumentException("There should be no error message for success.", nameof(error));
}
IsFailure = isFailure;
_error = error;
}
}
public struct Result
{
private static readonly Result _okResult = new Result(false, null);
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly ResultCommonLogic _logic;
public bool IsFailure => _logic.IsFailure;
public bool IsSuccess => _logic.IsSuccess;
public string Error => _logic.Error;
[DebuggerStepThrough]
private Result(bool isFailure, string error)
{
_logic = new ResultCommonLogic(isFailure, error);
}
[DebuggerStepThrough]
public static Result Ok()
{
return _okResult;
}
[DebuggerStepThrough]
public static Result Fail(string error)
{
return new Result(true, error);
}
[DebuggerStepThrough]
public static Result<T> Ok<T>(T value)
{
return new Result<T>(false, value, null);
}
[DebuggerStepThrough]
public static Result<T> Fail<T>(string error)
{
return new Result<T>(true, default(T), error);
}
/// <summary>
/// Returns first failure in the list of <paramref name="results"/>. If there is no failure returns success.
/// </summary>
/// <param name="results">List of results.</param>
[DebuggerStepThrough]
public static Result FirstFailureOrSuccess(params Result[] results)
{
foreach (Result result in results)
{
if (result.IsFailure)
return Fail(result.Error);
}
return Ok();
}
/// <summary>
/// Returns failure which combined from all failures in the <paramref name="results"/> list. Error messages are separated by <paramref name="errorMessagesSeparator"/>.
/// If there is no failure returns success.
/// </summary>
/// <param name="errorMessagesSeparator">Separator for error messages.</param>
/// <param name="results">List of results.</param>
[DebuggerStepThrough]
public static Result Combine(string errorMessagesSeparator, params Result[] results)
{
List<Result> failedResults = results.Where(x => x.IsFailure).ToList();
if (!failedResults.Any())
return Ok();
string errorMessage = string.Join(errorMessagesSeparator, failedResults.Select(x => x.Error).ToArray());
return Fail(errorMessage);
}
[DebuggerStepThrough]
public static Result Combine(params Result[] results)
{
return Combine(", ", results);
}
}
public struct Result<T>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly ResultCommonLogic _logic;
public bool IsFailure => _logic.IsFailure;
public bool IsSuccess => _logic.IsSuccess;
public string Error => _logic.Error;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly T _value;
public T Value
{
[DebuggerStepThrough]
get
{
if (!IsSuccess)
throw new InvalidOperationException("There is no value for failure.");
return _value;
}
}
[DebuggerStepThrough]
internal Result(bool isFailure, T value, string error)
{
if (!isFailure && value == null)
throw new ArgumentNullException(nameof(value));
_logic = new ResultCommonLogic(isFailure, error);
_value = value;
}
public static implicit operator Result(Result<T> result)
{
return result.IsSuccess ? Result.Ok() : Result.Fail(result.Error);
}
}
}