-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
executable file
·1291 lines (1234 loc) · 43 KB
/
index.html
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<!--
Bourbaki proving
(c) FeelUs
-->
<html>
<head>
<meta charset="utf-8">
<script src="jquery-2.2.0.js"></script>
<script src="parser.js"></script>
<script src="propsManager.js"></script>
</head>
<body>
<a href="https://github.com/feelusm/BourbakiProving/">это система проверки доказательств</a><br>
доказательство теории продолжайте в коде<br>
если в нем будет ошибка, произойдет исключение, которое можно увидеть в консоли браузера<br>
пункты, начинающиеся с <...> - можно разворачивать<br>
<button onclick="show_all()">развернуть все</button><button onclick="hide_all()">свернуть все</button>
<ul id="list">
</ul>
<script>
/*
Object.defineProperty(Array.prototype, 'last', {
enumerable:false,
get:function(){
return this[this.length-1];
}
})
*/
function Op(op,args){
if(this instanceof Op);else return new Op(op,args);
console.assert(['!','||'].indexOf(op)!=-1);
this.which = op;
this.args = args;
return this;
}
function not(arg){
if(typeof arg === 'string') arg = parse(arg)
return new Op('!',[arg]);
}
function or(arg1,arg2){
if(typeof arg1 === 'string') arg1 = parse(arg1)
if(typeof arg2 === 'string') arg2 = parse(arg2)
return new Op('||',[arg1,arg2]);
}
//implication
function imp(arg1,arg2){
return or(not(arg1),arg2);
}
copyProps(Parser,window);
var read_prim_expr = (str,pos)=> read_any(str,pos,collect,[
(str,pos)=>{
var r = read_rgx(str,pos,/^[A-Z_]+/);
if(!isGood(r)) return new FatalError(pos.x,'ожидался идентификатор');
if(!(r[0] in links)) return new FatalError(pos.x,'не объявлена ссылка '+r[0]);
return links[r[0]];
},
(str,pos)=>{
var r = read_seq(str,pos,need(1),[txt('(').exec,expr.exec,txt(')').exec]);
if(!isGood(r)) return addErrMessage(r,' - in "(expr)"');
return r;
}
]);
var read_expr_not = (str,pos)=> read_any(str,pos,collect,[
read_prim_expr,
(str,pos)=>{
var r = read_seq(str,pos,need(1),[txt('!').exec,read_expr_not]);
if(!isGood(r)) return addErrMessage(r,' - in "!expr"');
return not(r);
}
])
var read_expr_or = (str,pos)=> read_any(str,pos,collect,[
(str,pos)=>{
var r = read_seq(str,pos,need(0,2),[read_expr_not,txt('||').exec,read_expr_not]);
if(!isGood(r)) return addErrMessage(r,' - in "expr||expr"');
return or(r[0],r[1]);
},
read_expr_not
])
var read_expr_and = read_expr_or;// заменен на настоящий ниже
var read_expr_imp = (str,pos)=> read_any(str,pos,collect,[
(str,pos)=>{
var r = read_seq(str,pos,need(0,2),[read_expr_and,txt('=>').exec,read_expr_and]);
if(!isGood(r)) return addErrMessage(r,' - in "expr=>expr"');
return imp(r[0],r[1]);
},
read_expr_and
])
// добавляется eql
var expr = new Pattern(read_expr_imp);
function parse(str){
var res = expr.exec(str);
if(isGood(res)) return res;
throw JSON.stringify(res);
}
function Link(name){
if(this instanceof Link); else return new Link(name);
this.op = undefined; // паттерн
if(typeof name !== 'string'){
this.link = name; // паттерн для точного соответствия
if(name instanceof Link)
this.name = '['+name.name+']';
}
else this.name = name;
return this;
}
function MatchError(){
if(this instanceof MatchError);else return MatchError.apply(Object.create(MatchError.prototype),arguments)//throw 'you are fogot new';
this.OK = arguments.length==0;
if(this.OK) return this;
var args = Array.prototype.slice.call(arguments);
this.what = args.shift();
this.args = args;
return this;
}
OK = MatchError();
MatchError.prototype.print = function(){
if(this.OK) return 'OK'
var str = this.what +': ';
for(var i=0; i<this.args.length; i++)
str += printOp(this.args[i])+', '
return str.slice(0,str.length-2);
}
function eq_tree(op,pattern){
//рекурсивно сравниваем вплоть до адресов линков - они должны совпасть
if(op===pattern) return OK;
if(pattern instanceof Link || op instanceof Link) return MatchError('different links',op,pattern);
if(pattern instanceof Op && op instanceof Op);else throw 'unexpected type of pattern or op';
if(pattern.which!=op.which) return MatchError('different operations in links',op,pattern);
if(op.which=='!')
return eq_tree(op.args[0],pattern.args[0])
else if(op.which=='||'){
var x = eq_tree(op.args[0],pattern.args[0]);
if(!x.OK) return x;
return eq_tree(op.args[1],pattern.args[1]);
}
else throw 'unexpected op\'s type "'+op.which+'"';
}
function matchOp(op,pattern){
//рекурсивно сравниваем вплоть до линка в паттерне
if(pattern instanceof Op && op instanceof Link) return MatchError('very short op',op,pattern);
if(pattern instanceof Op && op instanceof Op)
if(op.which!=pattern.which) return MatchError('different operations',op,pattern);
else if(op.which=='!')
return matchOp(op.args[0],pattern.args[0])
else if(op.which=='||'){
var x = matchOp(op.args[0],pattern.args[0]);
if(!x.OK) return x;
return matchOp(op.args[1],pattern.args[1]);
}
else throw 'unexpected op\'s type "'+op.which+'"';
if(pattern instanceof Link);else throw 'unexpected type of pattern';
if(pattern.link!==undefined)
return eq_tree(op,pattern.link)
if(pattern.op===undefined) {
pattern.op=op;
return OK;
}
else
return eq_tree(op,pattern.op)
}
function Tau(link,op){
if(this instanceof Tau);else return new Tau(link,op);
this.link=link;
this.op=op;
}
function Replace(to,from,op){
if(this instanceof Replace);else return new Replace(to,from,op);
this.to=to;
this.from=from;
this.op=op;
}
var printArray = [];
printArray.push(function(op,parent_prio) { // !
var cur_prio = 0;
if(op.which=='!')
return '!'+printOp(op.args[0],cur_prio);
});
printArray.push(function(op,parent_prio) { // ||
var cur_prio = 1;
if(op.which=='||'){
if(parent_prio<=cur_prio) return '('+printOp(op.args[0],cur_prio)+'||'+printOp(op.args[1],cur_prio)+')';
else return printOp(op.args[0],cur_prio)+'||'+printOp(op.args[1],cur_prio);
}
})
printArray.push(function(op,parent_prio) { // =>
var cur_prio = 3;
if(op.which=='||' && op.args[0] instanceof Op && op.args[0].which=='!') {
if(parent_prio<=cur_prio) return '('+printOp(op.args[0].args[0],cur_prio)+'=>'+printOp(op.args[1],cur_prio)+')';
else return printOp(op.args[0].args[0],cur_prio)+'=>'+printOp(op.args[1],cur_prio);
}
})
function printOp(op,parent_prio){
if(op instanceof Link) return op.name;
if(op instanceof Op);else return '( '+JSON.stringify(op)+' )';
parent_prio = parent_prio===undefined ? 100 : parent_prio;
for(var i=printArray.length-1; i>=0; i--){
var res = printArray[i](op,parent_prio)
if(res) return res;
}
{
var strArr = [];
for(var i=0; i<op.args.length; i++)
strArr.push(printOp(op.args[i]));
return '('+op.which+' '+strArr.join(' ')+')'
}
//throw 'unknown operation';
}
Op.prototype.toJSON = function(){
return printOp(this);
}
function Theoreme(links,st,name){
if(this instanceof Theoreme);else return new Theoreme(links,st);
this.links=links;
this.st=st;
this.name = name;
}
//==============================================================
var DBconstructor = function(){this.nest=0;}
Object.setPrototypeOf(DBconstructor.prototype, Array.prototype);
DB = new DBconstructor();
// то же, что console.log, только с отступом
function hide($li,$list){
$list.hide().addClass('hidden');
$li.prepend('<span><...> </span>');
}
function show($li,$list){
$list.show().removeClass('hidden');
$li.children().first().remove();
}
function show_all(){
$('li').each((index,li)=>{
var $li = $(li)
var $list = $li.children().last();
if($list.length)
if($list.hasClass('hidden')) show($li,$list)
})
}
function hide_all(){
$('li').each((index,li)=>{
var $li = $(li)
var $list = $li.children().last();
if($list.length)
if(!$list.hasClass('hidden')) hide($li,$list)
})
}
DBconstructor.prototype.log = function(){
if(this.log_disable) return;
/*
var tabs = '';
for(var i=0; i<this.nest; i++) tabs+='\t';
arguments[0] = tabs+arguments[0];
*/
if(this.nest==0)
console.log.apply(console,arguments);
var $list = $('#list');
for(var i=0; i<this.nest; i++){
var $li = $list.children().last();
if($li.has('ul').length==0){
$li.append('<ul></ul>');
hide($li,$li.children().last())
}
$list = $li.children().last();
}
$('<li>'+arguments[0]+'</li>').appendTo($list).click(function(event){
var $li = $(this)
var $list = $li.children().last();
if($list.length){
if($list.hasClass('hidden')) show($li,$list)
else hide($li,$list)
}
event.stopPropagation();
})
}
// преобразование теоремы в строку
DBconstructor.prototype.print = function(i){
return '['+i+']'+(this[i].name?this[i].name:'')+': '+printOp(this[i].st);
}
DBconstructor.prototype.shortPrint = function(i){
return '['+i+']'+(this[i].name?this[i].name:'');
}
function addLinks(links,op){
if(op instanceof Link){
if(links.indexOf(op)==-1)links.push(op);
return;
}
if(op instanceof Op);else throw 'unknown type';
if(op.which=='!') addLinks(links,op.args[0])
else if(op.which=='||'){
addLinks(links,op.args[0]);
addLinks(links,op.args[1]);
}
else throw 'unknown op ('+op.which+')';
}
DBconstructor.prototype.addAxiom = function(st,name){
if(typeof st === 'string') st = parse(st)
to_n = this.find(st);
if(to_n!=-1) {
this.log('already exist '+printOp(st)+' : '+this.print(to_n));
return {st:st, no:to_n};
}
var x = this.add(st,name);
this.log('NEW AXIOME '+this.print(x.no));
return x;
}
DBconstructor.prototype.add = function(st,name){
var links = [];
addLinks(links,st);
var tmp = new Theoreme(links,st,name)
this.push(tmp);
return {st:st, no:this.length-1};
}
function ProveError(what){
Error.call(this, what);
this.message = what;
this.name = 'ProveError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ProveError);
}
else {
this.stack = (new Error()).stack;
}
}
ProveError.prototype = Object.create(Error.prototype);
function ManualProveError(what){
Error.call(this, what);
this.message = what;
this.name = 'ManualProveError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ManualProveError);
}
else {
this.stack = (new Error()).stack;
}
}
ManualProveError.prototype = Object.create(Error.prototype);
DBconstructor.prototype.find = function(from,hint_no){
var self = this;
function check(n){
//console.log('check '+n)
if(self.no_scheme) return eq_tree(from,self[n].st);// for makeTheoreme
self[n].links.forEach((link)=>{link.op=undefined})
return matchOp(from,self[n].st);
}
if(hint_no!==undefined){
if((typeof hint_no)!='number' || hint_no<0 || hint_no>=this.length)
throw new ProveError('bad hint_no: '+JSON.stringify(hint_no))
var err;
if((err = check(hint_no)).OK)
return hint_no;
else{
this.log(err.print()+' - in compare to '+printOp(this[hint_no].st));
return -1;
}
}
var errors=[];
for(var i=this.length-1; i>=0; i--) { // здесь реально пригодятся хеши
var err;
if((err=check(i)).OK){
//this.log(printOp(from)+' match to '+printOp(this[i].st))
return i;
}
errors.push(err);
}
//if(!DB.verbose)
return -1;
for(var i=0; i<errors.length; i++){
this.log(errors[i].print()+' - in compare to '+printOp(this[i].st));
}
return -1;
}
DBconstructor.prototype.check = function(st,hint){
if(typeof st === 'string') st = parse(st)
var i = hint ? this.find(st,hint.no) : this.find(st);
if(i==-1) throw new ProveError('no matches: '+printOp(st));
else this.log(printOp(st)+' match to '+this.print(i));
return {st:st, no:i};
}
DBconstructor.prototype.prove = function(from, to, {from:from_no_obj, because:because_no_obj, name}={}){
if(typeof from === 'string') from = parse(from)
if(typeof to === 'string') to = parse(to)
// проверка подсказок
var from_n;
if(from_no_obj){
if(typeof from_no_obj =='object' && 'no' in from_no_obj){
from_n = this.find(from,from_no_obj.no);
if(from_n==-1){
if(this.verbose)
this.log('can\'t from '+printOp(from)+' prove '+printOp(to))
throw new ProveError('"from" ('+printOp(from)+') don\'t match specified '+this.print(from_no_obj.no));
}
}
else throw 'from_no_obj has no "no" member';
}
var because_n;
if(because_no_obj){
if(typeof because_no_obj =='object' && 'no' in because_no_obj){
because_n = this.find(imp(from,to),because_no_obj.no);
if(because_n==-1){
if(this.verbose)
this.log('can\'t from '+printOp(from)+' prove '+printOp(to))
throw new ProveError('imp("from","to") ('+printOp(imp(from,to))+') don\'t match specified '+
this.print(because_no_obj.no));
}
}
else throw 'because_no_obj has no "no" member';
}
// проверка на already exist
to_n = this.find(to);
if(to_n!=-1) {
this.log('already exist '+printOp(to)+' : '+this.print(to_n)+
(!from_no_obj?' from undefined ':
' from '+this.shortPrint(from_n))+
(!because_no_obj?' because undefined ':
' because '+this.shortPrint(because_n)));
return {st:to, no:to_n};
}
// поиск
if(from_n===undefined){
from_n = this.find(from);
if(from_n==-1){
if(this.verbose)
this.log('can\'t from '+printOp(from)+' prove '+printOp(to))
throw new ProveError('can not find "from": '+printOp(from));
}
}
if(because_n===undefined){
because_n = this.find(imp(from,to));
if(because_n==-1){
if(this.verbose)
this.log('can\'t from '+printOp(from)+' prove '+printOp(to))
throw new ProveError('can not find imp("from","to"): '+printOp(imp(from,to)));
}
}
// попытки упростить
var from_ = from;
var to_ = to;
var changed = false;
this.log_disable = true;
while(true){
var simplified = simplify(imp(from,to));
if(!simplified ||
!(simplified instanceof Op) ||
simplified.which!='||' ||
!(simplified.args[0] instanceof Op) ||
simplified.args[0].which!='!'
) break;
if(this.find(simplified.args[0].args[0],from_n)==-1 ||
this.find(simplified,because_n)==-1){
if(0){ // осень часто неудачные
this.log_disable = false;
this.log('simplify is failed ('+printOp(from_)+' => '+printOp(to_)+
') --> ('+printOp(simplified.args[0].args[0])+' => '+printOp(simplified.args[1])+')');
}
break;
}
changed = true;
from = simplified.args[0].args[0];
to = simplified.args[1];
}
this.log_disable = false;
if(changed)
this.log('simplified (('+printOp(from_)+') => ('+printOp(to_)+')) --> (('+printOp(from)+') => ('+printOp(to)+'))');
// добавляем, сообщаем
var x = this.add(to,name);
this.log('prove '+this.print(x.no)+
(!from_no_obj?' from found '+this.print(from_n):
this.verbose?' (from '+this.print(from_n)+')':' from '+this.shortPrint(from_n))+
(!because_no_obj?' because found '+this.print(because_n):
this.verbose?' (because '+this.print(because_n)+')':' because '+this.shortPrint(because_n))
);
/*
for(var i=0; i<this.length; i++)
console.log(this.print(i))
*/
return x;
}
function forEachSubset(set,fun/*(subset)*/) { // по всем подмножествам (кроме пустого)
var set_switch = [];
for(var x in set)
set_switch.push({name:x,enabled:false})
function next_subset(st_sw){
for(var i=0; i<st_sw.length; i++)
if(st_sw[i].enabled)
st_sw[i].enabled = false
else{
st_sw[i].enabled = true;
return true;
}
return false;
}
for(;next_subset(set_switch);){
var subset={};
for(var i =0; i<set_switch.length; i++)// копируем в subset
if(set_switch[i].enabled)
subset[set_switch[i].name] = set[set_switch[i].name];
fun(subset);
}
}
function GCD(m,n) { // НОД двух чисел
var factor = 1;
while(true){
//НОД(0, n) = n; НОД(m, 0) = m; НОД(m, m) = m;
if(m==n)
if(m==0) throw 'GCD(0,0)'
else return factor*m;
if(m==0) return factor*n;
if(n==0) return factor*m;
//НОД(1, n) = 1; НОД(m, 1) = 1;
if(m==1 || n==1) return factor;
//Если m, n чётные, то НОД(m, n) = 2*НОД(m/2, n/2);
if(!(m&1) && !(n&1)){
factor<<=1;
m>>=1;
n>>=1;
}
//Если m чётное, n нечётное, то НОД(m, n) = НОД(m/2, n);
else if(!(m&1)) m>>=1;
//Если n чётное, m нечётное, то НОД(m, n) = НОД(m, n/2);
else if(!(n&1)) n>>=1;
//Если m, n нечётные и n > m, то НОД(m, n) = НОД((n-m)/2, m);
else if(n>m) n = (n-m)>>1;
//Если m, n нечётные и n < m, то НОД(m, n) = НОД((m-n)/2, n);
else m = (m-n)>>1;
}
}
function GCD_obj(obj) { // НОД свойств объекта
var nod;
for(var x in obj){
nod = obj[x];
break;
}
for(var x in obj)
nod = GCD(nod,obj[x]);
return nod;
}
function forEachDivisor(N,fun/*(divisor)*/) { // по всем делителям (кроме 1)
var simple_divs = [];
for(var i=2; i*i<=N; i++)//разбиваем N на простые множетели
if(N%i==0){
simple_divs.push({divisor:i,power:1,used:0});
N/=i;
while(N%i==0){
simple_divs[simple_divs.length-1].power++;
N/=i;
}
}
if(N>1) simple_divs.push({divisor:N,power:1,used:0});
function next_divisor(sd){
for(var i=0; i<sd.length; i++)
if(sd[i].used==sd[i].power)
sd[i].used = 0
else{
sd[i].used++;
return true;
}
return false;
}
for(;next_divisor(simple_divs);){
var divisor = 1;
for(var i =0; i<simple_divs.length; i++)
divisor*=Math.pow(simple_divs[i].divisor,simple_divs[i].used);
fun(divisor);
}
}
function simplify(tree){ // находит поддерево, повторяющееся 2 или более раз, такое, что
// переменные этих поддеревьев не содержатся вне этих поддеревьев
// заменяет эти поддеревья на одну переменную, и возвращает измененное дерево
// если не находит, возвращает undefined
function forEachSubtree(op,fun/*(op,stat)*/) { // return {size:n,stat:{[name]:m...}}
if(op instanceof Link){
var link_stat = {};
link_stat[op.name] = 1;
return {size:1,stat:link_stat};
}
else if(op instanceof Op);else throw 'unknown type';
var stat;
if(op.which=='!'){
var stat = forEachSubtree(op.args[0],fun);
stat.size++;
}
else if(op.which == '||'){
var stat = forEachSubtree(op.args[0],fun)
var stat2 = forEachSubtree(op.args[1],fun)
stat.size += stat2.size+1;
for(var x in stat2.stat){
if(x in stat.stat)
stat.stat[x]+=stat2.stat[x];
else
stat.stat[x] =stat2.stat[x];
}
}
else throw 'unknown op ('+op.which +')'
if(fun) fun(op,stat);
return stat;
}
function stat2string(stat) { // сортирует и в строку
var strs = [];
for(var x in stat)
strs.push(x+':'+stat[x]);
return strs.sort().join(';')
}
function makeResonablePredGroups(stat) { // формируем допустимые конфигурации для предгрупп
var predGroups = {};
forEachSubset(stat,function(sub_stat) {
var nod = GCD_obj(sub_stat);
if(nod>1)
forEachDivisor(nod,function(d){
var tmp_stat={}
for(var x in sub_stat)
tmp_stat[x] = sub_stat[x]/d;
predGroups[stat2string(tmp_stat)]={}
})
})
return predGroups;
}
function PredGroup(stat,size){
this.stat = stat;
this.size = size;
}
Object.setPrototypeOf(PredGroup.prototype, Array.prototype);
PredGroup.prototype.toJSON = function(){
var strings = [];
for(var i=0; i<this.length; i++)
strings.push(printOp(this[i].op));
return '('+this.size+','+stat2string(this.stat)+')['+strings.join(',')+']';
}
function fillPredGroups(tree,predGroups) { // добавляем поддеревья в предгруппы (создаем, если их нет)
var doSequence = [];
forEachSubtree(tree,function(op,stat){
//console.log(printOp(op)+' -before')
//console.log(JSON.stringify(predGroups))
//console.log(JSON.stringify(doSequence))
var statStr = stat2string(stat.stat);
if(statStr in predGroups){
var predGroupArr = predGroups[statStr];
if(stat.size in predGroupArr){
predGroupArr[stat.size].push({op:op,used:false})
for(var x in stat.stat)
console.assert(predGroupArr[stat.size].stat[x] == stat.stat[x]);
console.assert(predGroupArr[stat.size].size == stat.size);
}
else{
var tmp_stat = {};
for(var x in stat.stat)
tmp_stat[x] = stat.stat[x];
predGroupArr[stat.size] = new PredGroup(tmp_stat,stat.size)
predGroupArr[stat.size].push({op:op,used:false})
if(stat.size in doSequence)
doSequence[stat.size].push(predGroupArr[stat.size])
else
doSequence[stat.size] = [predGroupArr[stat.size]];
}
}
//console.log(printOp(op)+' -after')
//console.log(JSON.stringify(predGroups))
//console.log(JSON.stringify(doSequence))
})
return doSequence;
}
function sortCompressDoSequence(doSequence) { // сортируем предГруппы по размеру
var doSequence2 = [];
for(var x in doSequence)
doSequence2.push(x);
doSequence2.sort();
for(var i =0; i<doSequence2.length; i++)
doSequence2[i] = doSequence[doSequence2[i]]
return doSequence2;
}
function findGroup(doSequence,treeStat) { // ищем группу
for(var seq_i=0; seq_i<doSequence.length; seq_i++) // начиная с самых маленьких поддеревьев
for(var seq_j=0; seq_j<doSequence[seq_i].length; seq_j++){
var predGroup = doSequence[seq_i][seq_j]; // предГруппа
var x; for(x in predGroup.stat) break;
console.assert(treeStat[x]%predGroup.stat[x]==0);
var needed = treeStat[x]/predGroup.stat[x]; // сколько требуется поддеревьев
console.assert(needed>1);
var left = predGroup.length; // сколько поддеревьев из предгруппы не использовано
while(left>=needed){
var group = []; // начинаем формировать группу
var k;
for(k=0; k<predGroup.length; k++) // ищем первый элемент группы
if(!predGroup[k].used){
group.push(predGroup[k].op);
predGroup[k].used = true;
left--;
break;
}
var etalone = predGroup[k].op;
for(k++; k<predGroup.length && // по всей предГруппе
left+group.length>=needed && // пока есть возможность набрать группу
group.length<needed // пока группа не набрана
; k++) // из предГруппы формируем группу
if(!predGroup[k].used && eq_tree(predGroup[k].op,etalone).OK) {
group.push(predGroup[k].op);
predGroup[k].used = true;
left--;
}
if(group.length==needed)
return group;
}
}
return undefined;
}
function replaceGroup(group,tree) { // заменяет поддеревья из группы на переменную
// в первом поддереве группы найти Link
var op;
for(op = group[0]; op instanceof Op && op.which=='!' || op.which=='||'; op = op.args[0]) ;
var link = op;
// в корнях всех поддеревьев группы заменить which на другое
for(var i=0; i<group.length; i++)
group[i].replace = true;
// по всему дереву узлы с другим which заменить на link
function replaceOp(op){
if(op instanceof Op){
if(op.which=='||'){
var a,b;
if(op.args[0] instanceof Op && op.args[0].replace){
delete op.args[0].replace;
a = link;
}
else
a = replaceOp(op.args[0]);
//else throw 'replace link'
if(op.args[1] instanceof Op && op.args[1].replace){
delete op.args[1].replace;
b = link;
}
else
b = replaceOp(op.args[1]);
//else throw 'replace link'
return or(a,b);
}
else if(op.which=='!'){
var a;
if(op.args[0] instanceof Op && op.args[0].replace){
delete op.args[0].replace;
a = link;
}
else
a = replaceOp(op.args[0]);
return not(a);
//else throw 'replace link'
}
else throw 'unknown op ('+op.which+')';
throw 'not return 2';
}
else if(op instanceof Link)
return op;
else throw 'unknown type';
throw 'not return 1';
}
return replaceOp(tree);
}
var changed = false;
var treeStat = forEachSubtree(tree).stat;
var predGroups = makeResonablePredGroups(treeStat);
// объект, каждая строка stat индексирует
// объект(массив предГрупп), в котором каждый размер поддерева индексирует
// массив(предГруппа), набор из
// объект
// op - ссылку на поддерево
// used - использовалось ли в группе
// и свойства
// stat
// size
var doSequence = fillPredGroups(tree,predGroups);
// массив, каждый размер поддерева индексирует, а птом просто набор из
// массив, набор из
// указатель на предГруппу
//console.log(JSON.stringify(predGroups))
//console.log(JSON.stringify(doSequence))
doSequence = sortCompressDoSequence(doSequence);
//console.log(JSON.stringify(doSequence))
var group = findGroup(doSequence,treeStat)
//массив ссылок на дерево
if(group){
/*
var strArr = []
for(var i=0; i<group.length; i++)
strArr.push(printOp(group[i]));
console.log(strArr.join(','))
*/
var new_tree = replaceGroup(group,tree);
//console.log(printOp(tree))
//changed = true;
//if(eq_tree(tree,new_tree).OK)
//console.log('SIMPLIFY don\'t change: '+printOp(tree)+' '+printOp(new_tree))
return new_tree;
}
else
return undefined;
}
DB.log('============================ $3 Логические теории')
DB.log('---------------------------- п1 Аксиомы')
var links = {
A: new Link('A'),
B: new Link('B'),
B_: new Link('B_'),
C: new Link('C'),
D: new Link('D')
};
var A = links.A;
var B = links.B;
var B_ = links.B_;
var C = links.C;
var D = links.D;
var S1 = DB.addAxiom('A||A=>A','S1')
var S2 = DB.addAxiom('A=>A||B','S2')
var S3 = DB.addAxiom('A||B=>B||A','S3')
var S4 = DB.addAxiom('(A=>B)=>(C||A=>C||B)','S4')
function makeRule(name,description,target,fun){
return function(links,hints={}){
var strs = [];
for(var i=0; i<links.length; i++){
if(typeof links[i] ==='string')
links[i] = parse(links[i]);
strs.push(printOp(links[i]));
}
var tmp;
var trg = target(links);
DB.log(hints.name+': '+printOp(trg)+' _by_ '+name+' ['+strs.join(',')+'] '+description);
DB.nest++;
try{
tmp = DB.check(trg)
var str;
if(tmp instanceof Array){
str = tmp[tmp.length-1]
str = '('+(tmp.length-1)+')'+printOp(tmp.st)
}
else str = DB.print(tmp.no)
DB.log('fast exist '+str)
}
catch(err){
if(err instanceof ProveError){
hints.already_checked = DB.length
tmp = fun(links,hints);
}
else throw err;
}
DB.nest--;
return tmp;
}
}
DB.contradiction = makeRule('contradiction','A; !A -> B',([A,B])=>B, ([A,B],{True,False,name}={})=>{
var x = DB.prove(not(A),imp(A,B),{from:False, because:S2, name:'contradiction.'+name});
return DB.prove(A,B,{from:True, because:x, name});
})
DB.log('---------------------------- п2 Первые следствия')
DB.C6 = makeRule('C6','A=>B; B=>C -> A=>C',([A,B,C])=>imp(A,C), ([A,B,C],{first,second,name}={})=>{
var x = DB.prove(imp(B,C),imp(imp(A,B),imp(A,C)),{from:second, because:S4, name:'C6.'+name});
return DB.prove(imp(A,B),imp(A,C),{from:first, because:x, name});
})
var C7 = DB.C6([A,or(A,B),or(B,A)],{first:S2, second:S3, name:'C7'}); // A=>B||A
var C8 = DB.C6([A,or(A,A),A],{first:S2, second:S1, name:'C8'}); // A=>A
DB.C9 = makeRule('C9','B -> A=>B',([A,B])=>imp(A,B), ([A,B],{to,name}={})=>{
return DB.prove(B,imp(A,B),{from:to, because:C7, name});
})
var C10 = DB.prove('A=>A','A||!A',{from:C8, because:S3, name:'C10'})
var C11 = DB.check('A=>!!A', C10);
var C12_pre = DB.prove('B=>!!B','!A||B=>!A||!!B',{from:C11, because:S4, name:'C12_pre'})
var C12 = DB.C6(['!A||B','!A||!!B','!B=>!A'],{first:C12_pre, second:S3, name:'C12'}) // (A=>B)=>(!B=>!A)
var C13_pre = DB.prove('C||!A=>!A||C','(!B||C=>C||!A)=>(!B||C=>!A||C)',{from:S3, because:S4, name:'C13_pre'});
DB.C13 = makeRule('C13','A=>B -> (B=>C)=>(A=>C)',([A,B,C])=>imp(imp(B,C),imp(A,C)), ([A,B,C],{from,name}={})=>{
var x = DB.prove(imp(A,B),imp(not(B),not(A)),{from:from, because:C12, name:'C13_1.'+name});
x = DB.prove(imp(not(B),not(A)),imp(or(C,not(B)),or(C,not(A))),{from:x, because:S4, name:'C13_2.'+name})
x = DB.C6([or(not(B),C),or(C,not(B)),or(C,not(A))],{first:S3, second:x, name:'C13_3.'+name});
return DB.prove(imp(imp(B,C),or(C,not(A))),imp(imp(B,C),imp(A,C)),{from:x, because:C13_pre, name});
})
var x = DB.C13([imp(B,C),'C||!B','C||!A'], {from:S3, name:'My1_pre1'})
var y = DB.C6(['A=>B','!B=>!A','C||!B=>C||!A'], {first:C12, second:S4, name:'My1_pre2'})
x = DB.C6(['A=>B','C||!B=>C||!A','(B=>C)=>C||!A'], {first:y, second:x, name:'My1_pre3'})
DB.C6(['A=>B','(B=>C)=>C||!A','(B=>C)=>(A=>C)'], {first:x, second:C13_pre, name:'My1'})
DB.log('---------------------------- п3 Методы доказательства')
var C14_pre = DB.prove('!A=>(A=>B_)','((A=>B_)||!A)=>((A=>B_)||(A=>B_))', {from:S2, because:S4, name:'C14_pre'});
DB.C14 = makeRule('C14','A=>B; A=>(B=>B_) -> A=>B_',([A,B,B_])=>imp(A,B_), ([A,B,B_],{from,because,name}={})=>{
var x = DB.C13([A,B,B_],{from:from, name:'C14_1.'+name});
x = DB.C6([A,imp(B,B_),imp(A,B_)],{first:because, second:x, name:'C14_2.'+name});
x = DB.prove(imp(A,imp(A,B_)),or(imp(A,B_),not(A)), {from:x, because:S3, name:'C14_3.'+name});
x = DB.prove(or(imp(A,B_),not(A)),or(imp(A,B_),imp(A,B_)), {from:x, because:C14_pre, name:'C14_4.'+name});
return DB.prove(or(imp(A,B_),imp(A,B_)),imp(A,B_), {from:x, because:S1, name:name});
})
function makeTheoreme(pr_name,premise/*не схема*/,conseq,links,fun,hints={}) {
if(typeof premise === 'string') premise = parse(premise);
if(typeof conseq === 'string') conseq = parse(conseq);
var real_prove = DB.prove;
var real_check = DB.check;
var subDBs = makeTheoreme.subDBs;
var level = subDBs.length;
function hint_pop(hint){
if(level==0 && hint instanceof Array)
return hint[0];
else if(hint instanceof Array)
while(hint.length > level+1)
hint.pop()
return hint;
}
function hint_push(hint,x,level){
if(!(hint instanceof Array)) hint = [hint]
if(hint[level+1] !==undefined) throw 'overwrite in hint'
hint[level+1] = x;
return hint;
}
/*
* hint в стеке теорий - стек hint-ов в каждой теории,
* но может содержать пропуски:
* undefined говорит о том, что на данном уровне теоремы нет (и ее искать не стоит на данном уровне)
* null говорит, что на данном уровне может находиться теорема
*/
function is_fake(st,hint) { // если есть в верхней DB, то тоже, что check, иначе вернет undefined
if(hint){
if(hint[level+1]){
hint[level+1] = subDBs[level].check(st,hint[level+1])
return hint;
}
else if(hint[level+1]===null){
try{
hint[level+1] = subDBs[level].check(st)
return hint;
}
catch(err){if(err instanceof ProveError){
hint[level+1] = undefined;
return undefined;
}
else throw err;
}
}
else return undefined;
}
else{
hint = [];
try{
hint[level+1] = subDBs[level].check(st)
for(var i=0; i<=level; i++)
hint[i] = null;
return hint;
}
catch(err){if(err instanceof ProveError){
return undefined;
}
else throw err;
}
}
throw 'not implemented'
}
function fake_check(st,hint){
if(typeof st === 'string') st = parse(st)
var res = is_fake(st,hint);
if(res) return res;
DB.prove = real_prove;
DB.check = real_check;
try{
res = DB.check(st,hint_pop(hint));
}
catch(err){
if(err instanceof ProveError){
DB.prove = fake_prove;
DB.check = fake_check;
}
throw err;
}
DB.prove = fake_prove;
DB.check = fake_check;