in dsl-samples/tutorial/part1c-complete/ProseTutorial/Program.cs [78:128]
private static void LearnFromNewExample()
{
Console.Out.Write("Provide a new input-output example (e.g., \"(Sumit Gulwani)\",\"Gulwani\"): ");
try
{
string input = Console.ReadLine();
if (input != null)
{
int startFirstExample = input.IndexOf("\"", StringComparison.Ordinal) + 1;
int endFirstExample = input.IndexOf("\"", startFirstExample + 1, StringComparison.Ordinal) + 1;
int startSecondExample = input.IndexOf("\"", endFirstExample + 1, StringComparison.Ordinal) + 1;
int endSecondExample = input.IndexOf("\"", startSecondExample + 1, StringComparison.Ordinal) + 1;
if (startFirstExample >= endFirstExample || startSecondExample >= endSecondExample)
throw new Exception(
"Invalid example format. Please try again. input and out should be between quotes");
string inputExample = input.Substring(startFirstExample, endFirstExample - startFirstExample - 1);
string outputExample =
input.Substring(startSecondExample, endSecondExample - startSecondExample - 1);
State inputState = State.CreateForExecution(Grammar.InputSymbol, inputExample);
Examples.Add(inputState, outputExample);
}
}
catch (Exception)
{
throw new Exception("Invalid example format. Please try again. input and out should be between quotes");
}
var spec = new ExampleSpec(Examples);
Console.Out.WriteLine("Learning a program for examples:");
foreach (KeyValuePair<State, object> example in Examples)
Console.WriteLine("\"{0}\" -> \"{1}\"", example.Key.Bindings.First().Value, example.Value);
var scoreFeature = new RankingScore(Grammar);
ProgramSet topPrograms = _prose.LearnGrammarTopK(spec, scoreFeature, 4, null);
if (topPrograms.IsEmpty) throw new Exception("No program was found for this specification.");
_topProgram = topPrograms.RealizedPrograms.First();
Console.Out.WriteLine("Top 4 learned programs:");
var counter = 1;
foreach (ProgramNode program in topPrograms.RealizedPrograms)
{
if (counter > 4) break;
Console.Out.WriteLine("==========================");
Console.Out.WriteLine("Program {0}: ", counter);
Console.Out.WriteLine(program.PrintAST(ASTSerializationFormat.HumanReadable));
counter++;
}
}