Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

144
LINES

< > BotCompany Repo | #1017190 // Develop From Examples v3 [with function composition, OK]

JavaX source code (Dynamic Module) [tags: use-pretranspiled] - run with: Stefan's OS

Libraryless. Click here for Pure Java version (18077L/132K).

!7

set flag DynModule. // for transpilation

sclass DevelopFromExamples > DynTextArea {
  S whatToTry;
  transient ReliableSingleThread rst = new(r think);
  transient volatile PlanInMotion<Runnable> currentPlan;
  transient int delay = 0; //2000; // to see stuff

  visualize {
    final JLabel lblStatus = jlabel();
    awtEvery(lblStatus, 100, r { main.setText(lblStatus, planStatus()) });
    ret withCenteredButtons(centerAndSouthWithMargins(
      jhsplit(jSection("Examples (struct => struct)", super.visualize()), dm_printLogComponent()),
      vstackWithSpacing(
        jsection("Standard functions to try", onEnter(dm_fieldTextField('whatToTry), rst)),
        lblStatus
      )), "Think", rst, "Fresh", rThread fresh, "[disabled] Cancel", r cancel);
  }
  
  S planStatus() {
    PlanInMotion plan = currentPlan;
    if (plan == null) ret " ";
    ret "Steps done: " + l(plan.doneSteps) + ". Steps planned: " + l(plan.plannedSteps);
  }
  
  void cancel {
    PlanInMotion plan = currentPlan;
    if (plan != null) plan.cancelled = true;
  }
  
  void fresh {
    dm_refreshTranspiler();
    forgetTranspiledStandardFunctions(words(whatToTry));
    loadFunctions_clearCache();
    rst.trigger();
  }
  
  class Thinker {
    new PlanInMotion<Runnable> plan;
    new L<Pair<S>> examples;
    new L<Pair<O>> unstructedExamples;
    F2<O, O, Bool> equalsFunction;
    new LinkedHashSet<S> thingsThatWork;
    
    void go {
      currentPlan = plan;
      temp tempAfterwards(r { currentPlan = null; });
      temp tempEnableButton(findButton(dm_vis(), "Cancel"));
      
      clearPrintLog();
      loadFunctions_preferDiskCache();
    
      S text = rtrimAll(getText());
      Pair<File, Bool> examplesFile = ai_makeExamplesFile(text);
      if (examplesFile.b) print("Wrote: " + f2s(examplesFile.a));
      bool eqic = false;
    
      L<S> lines = tlftj(text);
      if (eq(first(lines), "splitAtEmptyLines"))
        lines = splitAtEmptyLines(text);
        
      for (S line : lines) pcall {
        if (eqic(line, "eqic")) eqic = true;
        L<S> l = splitAtDoubleArrow_bothDirections(line);
        if (l(l) == 2) {
          Pair<S> p = pair(
            tok_multiLineQuotesToStandardQuotes(first(l)),
            safeCanonicalizeStructure(tok_multiLineQuotesToStandardQuotes(second(l))));
          add(examples, p);
          add(unstructedExamples, pair(safeUnstruct(p.a), safeUnstruct(p.b));
        }
      }
      
      final File logFile = replaceExtension(examplesFile.a, ".log");
      final LineBuffer lineBuffer = new(voidfunc(S line) { appendToFile(logFile, line + "\n") });
      temp tempInterceptPrint(func(S s) -> Bool { lineBuffer.append(s); true; });
      
      print(localDateWithMilliseconds());
      print("Thinking about " + n2(examples, "example"));
      
      equalsFunction = eqic
          ? func(O a, O b) -> Bool { eqic((S) a, (S) b) }
          : func(O a, O b) -> Bool { eq(a, b) };
  
      // Make plan
      fL<S> functionsToTry = uniquify(standardFunctionsOnly(words(whatToTry)));
      
      for (fS s : functionsToTry) addToPlan(s);
      for (fS a : functionsToTry)
        for (fS b : listMinus(functionsToTry, a))
          addToPlan(a + "°" + b);
      
      for (Runnable r : plan.master())
        callF(r);
        
      print("\n" + (plan.cancelled ? "Cancelled" : "Done") + " after " + n2(plan.doneSteps, "step") + ". " +
        (empty(thingsThatWork) ? (plan.cancelled ? "Nothing worked so far." : "Nothing works.") : (plan.cancelled ? "Things that worked so far: " : "Things that work: ") + joinWithComma(thingsThatWork)));
      print();
    }
    
    void addToPlan(fS s) {
      plan.add(r {
        sleep(delay);
        F1<S, S> f = functionFromText(s);
        func(S in) -> S { struct(callAndMake_orDirect(s, unstruct(in))) };
        T3<S, S, O> counterExample = worksOnAllExamples_returnCounterExample(f, examples, equalsFunction);
        if (counterExample == null)
          print("WORKS: " + addAndReturn(thingsThatWork, s));
        else {
          print("Nope: " + s);
          bool exc = counterExample.c instanceof Throwable;
          print((exc ? "Exception on:    "
                     : "Wrong result on: ") + sfu(counterExample.a));
          print(       "Expected:        " + sfu(counterExample.b));
          if (exc)
            printStackTrace((Throwable) counterExample.c);
          else
            print(     "         Result: " + sfu(counterExample.c));
        }
      });
    }
  }
  
  void think {
    if (currentPlan != null) ret;
    new Thinker().go();
  }
  
  // Allows composed functions ("g°f") or simple function names
  F1<S, S> functionFromText(fS s) {
    fL<S> l = splitAtJavaToken(s, "°");
    if (l(l) == 2)
      ret func(S in) -> S {
        O o = unstruct(in);
        o = callAndMake_orDirect(second(l), o);
        o = callAndMake_orDirect(first(l), o);
        ret struct(o);
      };
    else
      ret func(S in) -> S { struct(callAndMake_orDirect(s, unstruct(in))) };
  }
}

Author comment

Began life as a copy of #1017185

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

-
Snippet ID: #1017190
Snippet name: Develop From Examples v3 [with function composition, OK]
Eternal ID of this version: #1017190/16
Text MD5: 27e0b7783028cc96b591935627eee783
Transpilation MD5: e488af1198ebe30f609d66c397f28729
Author: stefan
Category: javax / a.i.
Type: JavaX source code (Dynamic Module)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-08-20 11:13:52
Source code size: 5164 bytes / 144 lines
Pitched / IR pitched: No / No
Views / Downloads: 363 / 792
Version history: 15 change(s)
Referenced in: