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

42
LINES

< > BotCompany Repo | #1007704 // lispMatch

JavaX fragment (include)

1  
sbool lispMatch_debug;
2  
3  
static Map<S, Lisp> lispMatch(Lisp pat, Lisp input, S... variables) {
4  
  ret lispMatch(pat, input, asSet(variables));
5  
}
6  
7  
static Map<S, Lisp> lispMatch(Lisp pat, Lisp input, Collection<S> variables) {
8  
  new Map<S, Lisp> matches;
9  
  ret lispMatch_sub(pat, input, variables, matches) ? matches : null;
10  
}
11  
12  
static bool lispMatch_sub(Lisp pat, Lisp nl, Collection<S> variables, Map<S, Lisp> m) {
13  
  if (pat == null || nl == null) ret false;
14  
  if (pat.isLeaf() && variables.contains(pat.head)) {
15  
    if (lispMatch_debug) print("Var: " + pat.head + " => " + nl);
16  
    ret lispMatch_putMatch(m, pat.head, nl);
17  
  }
18  
    
19  
  if (neq(pat.head, nl.head)) ret false;
20  
  
21  
  // heads identical, proceed to children
22  
  int n = pat.size();
23  
  if (n != nl.size()) ret false;
24  
  
25  
  for (int i = 0; i < n; i++) {
26  
    if (lispMatch_debug) print("Sub " + i + ": " + pat.get(i) + " => " + nl.get(i));
27  
    if (!lispMatch_sub(pat.get(i), nl.get(i), variables, m))
28  
      false;
29  
  }
30  
      
31  
  true;
32  
}
33  
34  
static bool lispMatch_putMatch(Map<S, Lisp> matches, S key, Lisp val) {
35  
  if (matches.containsKey(key)) {
36  
    if (neq(matches.get(key), val))
37  
      false;
38  
      //fail("multi-matching not implemented");
39  
  } else
40  
    matches.put(key, val);
41  
  true;
42  
}

Author comment

Began life as a copy of #1002842

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1007704
Snippet name: lispMatch
Eternal ID of this version: #1007704/9
Text MD5: 69913da24cc32766f46658055ea6587e
Author: stefan
Category: javax / a.i.
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-04-13 18:15:19
Source code size: 1276 bytes / 42 lines
Pitched / IR pitched: No / No
Views / Downloads: 653 / 601
Version history: 8 change(s)
Referenced in: [show references]