-
Notifications
You must be signed in to change notification settings - Fork 11
/
metta_convert.pl
executable file
·1743 lines (1638 loc) · 75 KB
/
metta_convert.pl
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
/*
* Project: MeTTaLog - A MeTTa to Prolog Transpiler/Interpeter
* Description: This file is part of the source code for a transpiler designed to convert
* MeTTa language programs into Prolog, utilizing the SWI-Prolog compiler for
* optimizing and transforming functional/logic programs. It handles different
* logical constructs and performs conversions between functions and predicates.
*
* Author: Douglas R. Miles
* Contact: [email protected] / [email protected]
* License: LGPL
* Repository: https://github.com/trueagi-io/metta-wam
* https://github.com/logicmoo/hyperon-wam
* Created Date: 8/23/2023
* Last Modified: $LastChangedDate$ # You will replace this with Git automation
*
* Usage: This file is a part of the transpiler that transforms MeTTa programs into Prolog. For details
* on how to contribute or use this project, please refer to the repository README or the project documentation.
*
* Contribution: Contributions are welcome! For contributing guidelines, please check the CONTRIBUTING.md
* file in the repository.
*
* Notes:
* - Ensure you have SWI-Prolog installed and properly configured to use this transpiler.
* - This project is under active development, and we welcome feedback and contributions.
*
* Acknowledgments: Special thanks to all contributors and the open source community for their support and contributions.
*/
%*********************************************************************************************
% PROGRAM FUNCTION: Translate Prolog code to MeTTa code
%*********************************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% IMPORTANT: DO NOT DELETE COMMENTED-OUT CODE AS IT MAY BE UN-COMMENTED AND USED
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Defines a custom operator =~ with precedence 700 and xfx type, meaning it is a non-associative infix operator.
% This operator could be used for a specialized equality or pattern-matching operation in the program.
:- op(700,xfx,'=~').
% When the the `metta_interp` library is loaded, it makes sure the rest of the files are intially loaded in
% the correct order independent of which file is loaded first the needed predicates and ops are defined.
:- ensure_loaded(metta_interp).
% ===============================
% TESTING
% ===============================
%! fb is det.
%
% This predicate is used for testing purposes. It first compiles the program by calling 'make'.
% After that, it writes information for each clause of 'fb0', a test case rule, and executes the goals.
%
% The 'make' predicate is commonly used in Prolog for recompiling any modified predicates.
% The 'forall' loop iterates over all clauses of 'fb0', writing and calling the goals in the clauses.
%
% @example
% ?- fb.
% ;; ===========================================
% ;; ?- (two_pi(R) :- (pi(A), +(A, A, B), R is B)).
% ;; ?- factorial_tail_basic.
% ;; ?- funct.
% ;; ===========================================
fb :-
make, % Recompiles the program.
writeln(';; ==========================================='),
forall(
% Retrieve and execute each clause of 'fb0'.
(clause(fb0, Goal), write(';; '), writeq(?- Goal), nl, call(Goal)),
% After processing each clause, print a separator.
writeln(';; ===========================================')
).
%! fb0 is det.
%
% This rule provides test cases by showing mettalog sources. Each clause of 'fb0' uses 'show_mettalog_src'
% to display specific mettalog definitions. These are examples of how Prolog can show the structure of logical
% rules or concepts using 'show_mettalog_src/1'.
%
% @example
% ?- fb0.
% This will show the mettalog source for two_pi/1, factorial_tail_basic/0, and funct/0.
fb0 :- show_mettalog_src((two_pi(R) :- (pi(A), +(A, A, B), R is B))).
fb0 :- show_mettalog_src(factorial_tail_basic).
fb0 :- show_mettalog_src(funct).
%! print_metta_src is det.
% Displays mettalog sources for files or predicates that contain 'metta'.
% This predicate calls 'show_mettalog_src/0' to display all mettalog sources in the program.
% The 'show_mettalog_src' rule compiles the program and shows the mettalog sources for each
% source file that contains 'metta' in its name or content.
%
% This is useful for listing all relevant mettalog definitions after ensuring that the program is up-to-date.
%
% @example
% ?- print_metta_src.
print_metta_src :- show_mettalog_src.
%! show_mettalog_src is det.
%
% Compiles the Prolog program and displays the mettalog sources for each source file
% containing 'metta' in its file name.
%
% This predicate uses `make/0` to recompile the program, then iterates through all
% the source files, checking if the file name contains 'metta'. If so, it calls
% `show_mettalog_src/1` with the corresponding predicate.
%
% @example Compile and show mettalog sources:
% ?- show_mettalog_src.
% % This will compile the current Prolog program and print mettalog source details.
%
show_mettalog_src:-
% Recompile the program with make/0 to ensure all source changes are applied.
make,
% For all source files whose file names contain 'metta', display the mettalog source.
forall(
(
% Retrieve the predicate and its corresponding source file.
source_file(AsPred, File),
% Check if the file name contains 'metta'.
symbol_contains(File, metta)
),
% Show the mettalog source for the retrieved predicate.
show_mettalog_src(AsPred)
).
%! show_mettalog_src(+Spec) is det.
%
% Displays the mettalog source for predicates that match the specification `Spec`.
% This predicate handles various types of input to identify the predicates whose
% source should be displayed:
%
% - If `Spec` is in the form `F/A` (functor and arity), it directly shows the mettalog
% source for all predicates with functor `F` and arity `A`.
% - If `Spec` is a predicate term, it extracts the functor and arity and shows
% the source for predicates matching the functor and arity of the term.
% - If `Spec` is just the functor `F`, it shows the source for all predicates with
% that functor, regardless of arity.
% - If `Spec` is an atom `C` and matches part of a predicate functor, it shows the
% source for all predicates whose functor contains the atom `C`.
% - If none of the above match, it uses `show_cvts/1` as a fallback to display
% the mettalog source.
%
% @arg Spec The specification of the predicate(s) whose mettalog source is to be shown.
% This can be of the form `F/A` (functor and arity), a predicate term, or an atom.
%
% @example Show the mettalog source for a specific functor and arity:
% ?- show_mettalog_src(member/2).
%
% @example Show the mettalog source for all predicates with a specific functor:
% ?- show_mettalog_src(member).
%
% @example Show the mettalog source for all predicates whose functor contains 'metta':
% ?- show_mettalog_src('metta').
%
show_mettalog_src(F/A):- nonvar(F), !,
forall(current_predicate(F/A), show_mettalog_src(F,A)).
show_mettalog_src(AsPred):- functor(AsPred, F, A),\+ \+ current_predicate(F/A),!,forall(current_predicate(F/A),
show_mettalog_src(F,A)).
show_mettalog_src(F):- atom(F),\+ \+ current_predicate(F/_),!,forall(current_predicate(F/A), show_mettalog_src(F,A)).
show_mettalog_src(C):- atom(C),\+ \+ (current_predicate(F/_), once(atom_contains(F,C))),!,
forall((current_predicate(F/A), once(atom_contains(F,C))), show_mettalog_src(F,A)).
show_mettalog_src(C):- show_cvts(C), !.
% The 'show_space_src' rules compile the program and show space sources for each space predicate.
%! show_space_src is det.
%
% This predicate compiles the program using `make/0` and then iterates over all space predicates.
% For each space predicate, it calls `show_space_src/1` to display the space-related source code.
%
% This is useful for debugging or inspecting the Prolog predicates related to "space" concepts in the system.
%
% @example
% ?- show_space_src.
% % This will compile the program and display the source code for all space-related predicates.
%
show_space_src :-
% Recompile the program with make/0 to ensure all source changes are applied.
make,
% For all space predicates, display the source code.
forall(
space_preds(AsPred),
show_space_src(AsPred)
).
% Similar to the 'show_mettalog_src' rules, these rules handle different cases for 'show_space_src'
% with different input parameters and perform various checks and actions based on the type and value of the input.
%! show_space_src(+Spec) is det.
%
% This predicate displays the source code for space-related predicates that match the provided specification `Spec`.
% It handles different types of input to identify the relevant predicates:
%
% - If `Spec` is in the form `F/A` (functor and arity), it shows the source code for all predicates with functor `F` and arity `A`.
% - If `Spec` is a predicate term, it extracts the functor and arity, and shows the source code for predicates with matching functor and arity.
% - If `Spec` is just the functor `F`, it shows the source for all predicates with that functor, regardless of arity.
% - If `Spec` is an atom `C` and matches part of a predicate functor, it shows the source for all predicates whose functor contains `C`.
% - If none of the above match, it uses `show_cvts/1` as a fallback to display converted terms.
%
% @arg Spec The specification of the predicate(s) whose space-related source code is to be shown.
% This can be in the form `F/A` (functor and arity), a predicate term, or an atom.
%
% @example Show the space-related source code for a specific functor and arity:
% ?- show_space_src(member/2).
%
% @example Show the space-related source for all predicates with a specific functor:
% ?- show_space_src(member).
%
% @example Show the space-related source for all predicates whose functor contains 'space':
% ?- show_space_src('space').
%
show_space_src(F/A):- nonvar(F),!, forall(current_predicate(F/A), show_space_src(F,A)).
show_space_src(AsPred):- functor(AsPred,F,A), \+ \+ current_predicate(F/A), !, forall(current_predicate(F/A),
show_space_src(F,A)).
show_space_src(F):- atom(F), \+ \+ current_predicate(F/_),!, forall(current_predicate(F/A), show_space_src(F,A)).
show_space_src(C):- atom(C), \+ \+ (current_predicate(F/_),once(atom_contains(F,C))),!,
forall((current_predicate(F/A),once(atom_contains(F,C))), show_space_src(F,A)).
show_space_src(C):- show_cvts(C),!.
% 'show_cvts' rule processes a term, performing different actions based on the structure of the term.
%! show_cvts(+Term) is det.
%
% Processes the given `Term`, converting lists in S-expression form to Prolog terms using `sexpr_s2p/2`.
% If the result is not a list, recursively processes the converted term.
%
% @arg Term The input term to process, which can be a list or any Prolog term.
%
show_cvts(Term) :-
once((is_list(Term), sexpr_s2p(Term, PF))),
\+ is_list(PF), !,
show_cvts(PF).
show_cvts(Term):- iz_conz(Term),!, ppc(orig,Term),Term = FunctForm,
functs_to_preds(FunctForm,Prolog), ppc(preds,Prolog),
preds_to_functs(Prolog,NFunctForm), ppc(functs,NFunctForm).
show_cvts(Term):- ppc(orig,Term),
preds_to_functs(Term,FunctForm), ppc(functs,FunctForm),
functs_to_preds(FunctForm,Prolog), ppc(preds,Prolog).
% 'show_mettalog_src' for specific predicate, prints metta clauses if they exist in the source file containing 'metta'.
%! show_mettalog_src(+F, +A) is det.
%
% Displays the mettalog clauses for a specific predicate with functor `F` and arity `A` if they exist in
% a source file that contains 'metta' in its name.
%
% - It first checks if the predicate has clauses.
% - Then, it checks if the source file for the predicate contains 'metta' in its name.
% - If these conditions are met, it retrieves and prints all the clauses for the predicate.
%
% @arg F The functor of the predicate.
% @arg A The arity of the predicate.
%
% @example Show the mettalog source for a predicate:
% ?- show_mettalog_src(my_predicate, 2).
%
show_mettalog_src(F, A) :-
functor(Head, F, A),
ignore((
% Check if the predicate has clauses and its source file contains 'metta'.
predicate_property(Head, number_of_clauses(_)),source_file(Head, File),atom_contains(File, metta),!,nl,
% Find all clauses of the predicate and print them.
findall((Head :- Body), clause(Head, Body), Clauses),print_metta_clauses(Clauses))),
nl.
% 'print_metta_clauses' rule is handling the printing of metta clauses.
% It checks the form of the input clauses and calls 'print_metta_clause' accordingly.
%! print_metta_clauses(+Clauses) is det.
%
% Handles the printing of metta clauses. It checks the form of the input clauses and delegates
% to `print_metta_clause/2` for each clause.
%
% - If the input is an empty list, it does nothing.
% - If the input is a single clause, it prints it directly.
% - If the input is a list of clauses, it combines them into a single clause before printing.
%
% @arg Clauses The list of clauses to be printed.
%
print_metta_clauses([]) :- !.
print_metta_clauses([Head :- Body]) :- !,
print_metta_clause(Head, Body).
print_metta_clauses(Clauses) :-
combine_clauses(Clauses, Head, Body), !,
print_metta_clause(Head, Body).
%! print_metta_clause(+Head, +Body) is det.
%
% Prints a single metta clause consisting of a head and body, then processes it further using `show_cvts/1`.
%
% @arg Head The head of the clause.
% @arg Body The body of the clause.
%
print_metta_clause(Head, Body) :-
print_metta_clause0(Head, Body),
show_cvts(Head :- Body).
% 'print_metta_clause0' rule prints metta clauses based on the body.
% It transforms the body to a list, if needed, and prints it in a sequential form.
%! print_metta_clause0(+Head, +Body) is det.
%
% Prints metta clauses by transforming the body as needed and outputting it in a sequential form.
%
% - If the body is `true`, it prints the clause as `Head = True`.
% - If the body is `false`, it prints the clause as `Head = False`.
% - If the body contains multiple conjuncts, it converts the body to a list, processes it into sequential form,
% and prints the result.
%
% @arg Head The head of the clause.
% @arg Body The body of the clause, which can be a single condition or a conjunction.
%
% @example Print a clause with a true body:
% ?- print_metta_clause0(my_pred, true).
%
print_metta_clause0(Head,Body):- Body == true,!, pp_metta([=,Head,'True']).
print_metta_clause0(Head,Body):- Body == false,!, pp_metta([=,Head,'False']).
print_metta_clause0(Head,Body):- conjuncts_to_list(Body,List), into_sequential([':-'],List,SP),pp_metta([=,Head,SP]).
% =========================================
% STERM -> PTERM
% =========================================
%! iz_exact_symbol(+N, ?P) is nondet.
%
% This predicate checks whether `N` is an exact symbol and optionally unifies it with `P`.
% It handles specific symbols like ':-', '?-', and '??' directly, and fails if `N` is not an atom.
%
% - If `N` is not an atom, the predicate fails.
% - If `P` is provided and nonvar, it recursively checks if `P` matches the exact symbol corresponding to `N`.
% - For certain predefined symbols (`':-'`, `'?-'`, and `'??'`), it returns their matching symbols.
%
% @arg N The symbol to check or convert.
% @arg P Optionally, the corresponding symbol to unify with `N`.
%
% @example Check if ':-' is an exact symbol:
% ?- iz_exact_symbol(':-', X).
% X = ':-'.
%
% @example Check if '??' has an exact match:
% ?- iz_exact_symbol('??', X).
% true.
%
iz_exact_symbol(N,_):- \+ atom(N),!,fail.
iz_exact_symbol(N,P):- nonvar(P),!,iz_exact_symbol(N,PP),zalwayz(P=PP).
iz_exact_symbol(':-',':-').
iz_exact_symbol('?-','?-').
iz_exact_symbol('??',_).
%:- baseKB:ensure_loaded(logicmoo('plarkc/logicmoo_i_cyc_rewriting')).
%! maybe_varz(+S, +Name, -Var) is nondet.
%
% This predicate checks if `S` is the symbol `'?'` and `Name` is an atom. If both conditions are true, it unifies `Var` with the Prolog variable notation `'$VAR'(Name)`.
%
% - If `S` is the symbol `'?'` and `Name` is an atom, it succeeds and binds `Var` to `'$VAR'(Name)`.
% - Otherwise, it fails.
%
% @arg S The symbol to check (expected to be `'?'`).
% @arg Name The name of the variable, expected to be an atom.
% @arg Var The resulting Prolog variable notation `'$VAR'(Name)`.
%
% @example
% ?- maybe_varz('?', x, Var).
% Var = '$VAR'(x).
%
maybe_varz(S, Name, '$VAR'(Name)) :- S == '?',atom(Name), !.
%% sexpr_s2p(Fn,?VAR, ?V) is det.
%
%! sexpr_s2p(+Sterm, -Pterm) is det.
%
% Converts an S-expression (`Sterm`) into a Prolog term (`Pterm`).
%
% - If `Sterm` is a compound term in the form `H=B`, it attempts to compile the term using `compile_for_assert/3`,
% and then converts the compiled clause into a Prolog term.
% - Otherwise, it delegates the conversion to `sexpr_s2p/4`, starting with the default function `progn` and position `1`.
%
% @arg Sterm The S-expression input to be converted (can be a compound or other form).
% @arg Pterm The resulting Prolog term.
%
% @example Convert an S-expression:
% ?- sexpr_s2p((pi(A) = B), P).
% P = ... (Prolog term).
%
sexpr_s2p(HB, P) :- fail,compound(HB),HB =~ (H = B),compile_for_assert(H, B, Cl),clause_to_code(Cl, P), !.
sexpr_s2p(S, P) :- sexpr_s2p(progn, 1, S, P).
%! clause_to_code(+Clause, -Code) is det.
%
% Converts a Prolog clause into its code representation. This handles different cases:
%
% - If `Clause` is a free term variable (`ftVar`), it is left unchanged.
% - If the body (`B`) of the clause is `true`, it combines the head (`H`) and body into the code form.
% - In all other cases, the clause is returned unchanged.
%
% @arg Clause The input Prolog clause to be converted.
% @arg Code The resulting code representation of the clause.
%
clause_to_code(P,P):- is_ftVar(P),!.
%clause_to_code(P:-True,P):- True == true,!.
clause_to_code((H:-B),P):- B==true, !, combine_code(B,H,P).
clause_to_code(P,P).
%
%%%%%%%%%%%%%%%%%%%% START sexpr_s2p clauses %%%%%%%%%%%
%
%! sexpr_s2p(+Fn, +Nth, +Sterm, -Pterm) is det.
%
% Converts an S-expression (`Sterm`) into a Prolog term (`Pterm`), handling various cases like free variables,
% exact symbols, and atom-to-variable mappings.
%
% @arg Fn The function name associated with the S-expression (used in specific cases).
% @arg Nth The argument position being processed (used in specific cases).
% @arg Sterm The S-expression input to be converted.
% @arg Pterm The resulting Prolog term.
%
% If the S-expression is a free term variable (ftVar), it is returned unchanged.
sexpr_s2p(_Fn, _Nth, VAR, VAR) :- is_ftVar(VAR), !.
% If the S-expression is an exact symbol, it is converted using iz_exact_symbol/2.
sexpr_s2p(_Fn, _Nth, S, P) :- iz_exact_symbol(S, P), !.
% If the S-expression is of the form #(S), it is treated as a special exact symbol.
sexpr_s2p(_Fn, _Nth, '#'(S), P) :- iz_exact_symbol(S, P), !.
% If the S-expression is an atom, it is converted into a Prolog variable with '$VAR'(Name).
sexpr_s2p(_Fn, _Nth, VAR, '$VAR'(Name)) :- atom(VAR), svar(VAR, Name), !.
% If the S-expression is an empty list and the function allows lists, return the empty list.
sexpr_s2p(Fn, Nth, S, P) :- S == [],iz_fun_argz(Fn, Nth), !, P = S.
%sexpr_s2p(Fn,Nth,S,P):- expects_type(Fn,Nth,Type),will_become_type(Type,S,P),!.
% - If `Sterm` is a list, it checks if `F` is a system predicate with the appropriate arity.
% - It then recursively converts the arguments (`SList`) and constructs the Prolog term using `P =.. [Pred|PList]`.
sexpr_s2p(_Fn,_Nth,[F|SList],P):- is_list(SList), length(SList,Len),is_syspred(F,Len,Pred),
sexpr_s2p_arglist(F,1,SList,PList), !, P=..[Pred|PList].
% Disable singleton variable warnings.
%
% The directive `:- style_check(-singleton)` is used to turn off warnings
% related to singleton variables in Prolog. Singleton variables are those
% that appear only once in a clause, which can sometimes indicate a typo or
% an unused variable.
%
% This is useful when singleton variables are intentional and no warning is needed.
%
:- style_check(-singleton).
% If the function and argument position allow, convert the first element of the list (`S`)
% and the remaining list (`SList`) recursively.
sexpr_s2p(Fn,Nth,[S|SList],[P|PList]):- iz_fun_argz(Fn,Nth),!,sexpr_s2p(S,P), sexpr_s2p(Fn,Nth,SList,PList).
% If the first element is not an atom or `SList` is not a list, recursively convert both `S` and `SList` with `list(Fn)` context.
sexpr_s2p(Fn,Nth,[S|SList],[P|PList]):- ( \+ atom(S) ; \+ is_list(SList)), !,sexpr_s2p(list(Fn),Nth,S,P),
sexpr_s2p(list(Fn),Nth,SList,PList).
% If the first element `S` is a known quoter, convert the subsequent list (`STERM0`) and combine it into a Prolog term.
sexpr_s2p(_Fn,_Nth,[S,STERM0],PTERM):- iz_quoter(S),sexpr_s2p_pre_list(S,0,STERM0,STERM), !,PTERM=..[S,STERM],!.
% If `S` is an atom and `SList` is empty, construct a compound term with arity 0.
sexpr_s2p(_Fn,_Nth,[S|SList],P):- atom(S), SList == [], compound_name_arity(P,S,0).
% sexpr_s2p(Fn,Nth,List,PTERM):- append(Left,[S,Name|TERM],List),maybe_varz(S,Name,Var),!,append(Left,[Var|TERM],NewList), sexpr_s2p(Fn,Nth,NewList,PTERM).
% sexpr_s2p(Fn,Nth,[S|TERM],dot_holds(PTERM)):- \+ (is_list(TERM)),sexpr_s2p_arglist(Fn,Nth,[S|TERM],PTERM),!.
%sexpr_s2p(Fn,Nth,[S|TERM],PTERM):- \+ atom(S),sexpr_s2p_arglist(Fn,Nth,[S|TERM],PTERM),!.
/*
sexpr_s2p(Fn,Nth,[S,Vars|TERM],PTERM):- nonvar(S),
call_if_defined(common_logic_snark:iz_quantifier(S)),
zalwayz((sexpr_s2p_arglist(Fn,Nth,TERM,PLIST),
PTERM =~ [S,Vars|PLIST])),!.
*/
% sexpr_s2p(progn,_,[S|TERM],PTERM):- S==AND,!,zalwayz((maplist(sexpr_s2p,TERM,PLIST),list_to_conjuncts(',',PLIST,PTERM))).
%sexpr_s2p(Fn,Nth,[S|TERM],PTERM):- (number(S); (atom(S),fail,atom_concat_or_rtrace(_,'Fn',S))),sexpr_s2p_arglist(Fn,Nth,[S|TERM],PTERM),!.
%sexpr_s2p(Fn,Nth,[S],O):- is_ftVar(S),sexpr_s2p(Fn,Nth,S,Y),!,z_univ(Fn,Nth,O,[Y]),!.
%sexpr_s2p(Fn,Nth,[S],O):- nonvar(S),sexpr_s2p(Fn,Nth,S,Y),!,z_univ(Fn,Nth,O,[Y]),!.
%sexpr_s2p(Fn,Nth,[S|TERM],PTERM):- S==and,!,zalwayz((maplist(sexpr_s2p,TERM,PLIST),list_to_conjuncts(',',PLIST,PTERM))).
% sexpr_s2p(Fn,Nth,[S|TERM],PTERM):- iz_va_relation(S),!,zalwayz((maplist(sexpr_s2p,TERM,PLIST),list_to_conjuncts(S,PLIST,PTERM))).
%sexpr_s2p(Fn,Nth,[S|TERM],PTERM):- iz_relation_sexpr(S),zalwayz((sexpr_s2p_arglist(Fn,Nth,TERM,PLIST),PTERM =~ [S|PLIST])),!.
%sexpr_s2p(Fn,Nth,STERM,PTERM):- STERM =~ [S|TERM],sexpr_s2p_arglist(Fn,Nth,TERM,PLIST),z_univ(Fn,Nth,PTERM,[S|PLIST]),!.
% Convert the list `[S|STERM0]` by processing the rest of the list with `sexpr_s2p_pre_list/4`
% and then converting the arguments (`STERM`) into a Prolog term list (`PLIST`).
sexpr_s2p(Fn,Nth,[S|STERM0],PTERM):-
sexpr_s2p_pre_list(Fn,Nth,STERM0,STERM),
sexpr_s2p_arglist(S,1,STERM,PLIST), z_univ(Fn,Nth,PTERM,[S|PLIST]),!.
% If the input `VAR` is already in Prolog term format, return it unchanged.
sexpr_s2p(_Fn,_Nth,VAR,VAR).
%
%%%%%%%%%%%%%%%%%%%% END sexpr_s2p clauses %%%%%%%%%%%
%
%! expects_type(+Fn, +Nth, -Type) is nondet.
%
% Determines the expected type of the Nth argument for the function Fn.
% Uses `get_operator_typedef/4` to get the parameters and return type, and
% selects the type at position Nth.
%
% @arg Fn The function to check.
% @arg Nth The index of the argument (0-based).
% @arg Type The expected type of the argument.
%
% @example
% ?- expects_type(my_function, 1, Type).
% Type = param1_type.
%
expects_type(Fn, Nth, Type) :-
get_operator_typedef(Self, Fn, Params, RetType),
nth0(Nth, [RetType | Params], Type),
nonvar(Type).
%! will_become_type(+Type, +S, -P) is det.
%
% Ensures S becomes of the specified Type, possibly coercing it.
%
% @arg Type The target type.
% @arg S The input value.
% @arg P The result after type adjustment.
%
will_become_type(Type, S, P) :-
% Try adjusting the argument types using try_adjust_arg_types/7.
try_adjust_arg_types(=, _RetType, 88, _Self, [Type], [S], [PS]),PS = P, !.
will_become_type(Type, S, P) :-
% If S is a free type variable, unify P with S directly.
is_ftVar(S), !, P = S.
will_become_type(Type, S, P) :-
% If S has a type, check if it is a subtype of the target Type.
% If it is, unify P with S, otherwise, coerce S to the target Type.
get_type(S, T), !,(is_subtype(T, Type) -> S = P ; P = coerce(Type, S)).
will_become_type(_Type, S, P) :-
% If no other conditions apply, simply unify S with P.
!, S = P.
%! is_subtype(+T, +TT) is nondet.
%
% Checks if T is a subtype of TT. Unifies T and TT if they are considered equivalent.
%
% @arg T The type to check.
% @arg TT The target type to compare against.
%
is_subtype(T, TT) :-
% If T and TT are structurally identical, unify them.
T =@= TT, !, T = TT.
is_subtype(T, TT) :-
% If T is already equal to TT, succeed.
T = TT, !.
%! iz_quoter(+Quoter) is nondet.
%
% Checks if Quoter is a valid quoting operator.
% This predicate defines different quoting operators based on certain conditions.
%
% @arg Quoter The quoter to check.
%
iz_quoter('#BQ') :-
% '#BQ' is a quoter if the system is in Common Lisp mode.
iz_common_lisp.
iz_quoter('#COMMA') :-
% '#COMMA' is a quoter if the system is in Common Lisp mode.
iz_common_lisp.
iz_quoter('quote').
% 'quote' is always considered a quoter.
iz_quoter(superpose).
% 'superpose' is always considered a quoter.
%! iz_fun_argz(+Fun, +ArgCount) is nondet.
%
% Determines the number of arguments (ArgCount) that a given function or construct (Fun) expects.
%
% @arg Fun The function or construct whose argument count is being checked.
% @arg ArgCount The number of expected arguments for Fun.
%
iz_fun_argz(list(_), _).
% The 'list' construct can take any number of arguments.
iz_fun_argz(defmacro, 2).
% 'defmacro' expects 2 arguments.
iz_fun_argz(defun, 2).
% 'defun' expects 2 arguments.
iz_fun_argz(let, 1).
% 'let' expects 1 argument.
iz_fun_argz('let*', 1).
% 'let*' expects 1 argument.
iz_fun_argz('member', 2).
% 'member' expects 2 arguments.
% iz_fun_argz('let*', 2).
iz_fun_argz(F, 1) :-
% Any function that is a quoter (checked via iz_quoter/1) expects 1 argument.
iz_quoter(F).
%! z_functor(+F) is nondet.
%
% Checks if F is a valid functor by ensuring it is an atom and does not start
% with specific characters ('?' or '$').
%
% @arg F The functor to check.
%
z_functor(F) :-
% Fail if F is not an atom.
\+ atom(F), !, fail.
z_functor(F) :-
% Succeed if F does not start with '?'.
\+ atom_concat('?', _, F).
z_functor(F) :-
% Succeed if F does not start with '$'.
\+ atom_concat('$', _, F).
%! z_univ(+Fn, +Nth, ?P, ?S) is det.
%
% Unifies the term `P` with a compound term based on `F` and `ARGS`, or directly with `S`.
% Handles different cases depending on `Nth`.
%
% @arg Fn Functor (not directly used).
% @arg Nth Arity or position indicator.
% @arg P Term to unify with a compound term or `S`.
% @arg S List or term to unify with `P`.
%
% @example
% ?- z_univ(_, _, P, [functor, [arg1, arg2]]).
% P = functor(arg1, arg2).
%
% z_univ(_Fn, 1, S, S) :- !.
%
z_univ(_Fn, _, P, [F|ARGS]) :-
% Unify P with a compound term of functor F and its arguments.
z_functor(F), is_list(ARGS), length(ARGS, A), l_arity_l(F, A),compound_name_arguments(P, F, ARGS), !.
z_univ(_Fn, 0, P, [F|ARGS]) :-
% Similar to previous, but Nth is 0.
z_functor(F), is_list(ARGS), compound_name_arguments(P, F, ARGS), !.
z_univ(_Fn, _Nth, P, [F|ARGS]) :-
% General case for any Nth, unifies P with a compound term.
z_functor(F), is_list(ARGS), compound_name_arguments(P, F, ARGS), !.
z_univ(_Fn, _Nth, P, S) :-
% Fallback: unify P with S directly.
P = S.
%! l_arity_l(+F, +A) is det.
%
% Checks or assigns the arity `A` of the functor `F`. The predicate determines
% the arity of specific functors or uses rules to infer the arity if possible.
% Default arity is 1 if no specific case is matched.
%
% @arg F The functor whose arity is being checked or assigned.
% @arg A The arity (number of arguments) of the functor.
%
% @example
% ?- l_arity_l(function, A).
% A = 1.
l_arity_l(F, A) :-
% Check if the arity of functor F matches A by calling arity/2 predicate.
clause_b(arity(F, A)).
l_arity_l(function, 1).
% Functor 'function' always has arity 1.
l_arity_l(quote, 1).
% Functor 'quote' always has arity 1.
l_arity_l('#BQ', 1) :-
% Functor '#BQ' has arity 1 in Common Lisp context.
iz_common_lisp.
l_arity_l(F, A) :-
% If F/A is a current predicate, arity is accepted as valid.
current_predicate(F/A).
l_arity_l(_, 1).
% Default case: assume arity of 1.
%! sexpr_s2p_arglist(+Fn, +Nth, ?SExpr, ?PExpr) is det.
%
% Converts a list of S-expressions (`SExpr`) into Prolog expressions (`PExpr`).
% Handles different cases depending on the structure of `SExpr` and whether it is
% a variable or a list. The conversion uses `sexpr_s2p/4` to handle individual elements.
%
% @arg Fn Functor used for conversion (not directly used in all clauses).
% @arg Nth Position or index during processing, adjusted as needed.
% @arg SExpr The input S-expression (can be a variable or a list).
% @arg PExpr The output Prolog expression corresponding to `SExpr`.
%
% @example
% ?- sexpr_s2p_arglist(_, 1, [a, b, c], PList).
% PList = [a, b, c].
sexpr_s2p_arglist(_Fn, _, VAR, VAR) :-
% Base case: if `VAR` is a free term variable, leave it unchanged.
is_ftVar(VAR), !.
sexpr_s2p_arglist(Fn, Nth, [S|SList], [P|PList]) :-
% Recursively process list: convert head `S` to `P`, then process the tail.
sexpr_s2p(Fn, Nth, S, P),
(Nth > 0 -> Nth2 is Nth + 1 ; Nth2 = 0), % Increment Nth if positive, else set to 0.
sexpr_s2p_arglist(Fn, Nth2, SList, PList), !.
sexpr_s2p_arglist(Fn, Nth, S, P) :-
% Convert a single S-expression `S` into a Prolog expression `P`.
sexpr_s2p(Fn, Nth, S, P), !.
sexpr_s2p_arglist(_Fn, _Nth, VAR, VAR).
% Fallback: if `VAR` is neither a list nor an S-expression, leave it unchanged.
%! sexpr_s2p_pre_list(+Fn, +Nth, ?STerm, ?PTerm) is det.
%
% Pre-processes a list of S-expressions (`STerm`) to produce corresponding Prolog terms (`PTerm`).
% Handles different cases, including non-compound terms, non-list structures, and recursively
% processing nested lists. Uses `sexpr_s2p/4` for the actual conversion.
%
% @arg Fn Functor used during processing.
% @arg Nth Position or index used during processing (not always used).
% @arg STerm Input S-expression (could be a term or a list).
% @arg PTerm Resulting Prolog term after conversion.
%
% @example
% ?- sexpr_s2p_pre_list(_, _, [a, [b, c], d], PTerm).
% PTerm = [a, [b, c], d].
sexpr_s2p_pre_list(_Fn, _, STERM, STERM) :-
% If `STERM` is not compound, return it unchanged.
\+ compound(STERM), !.
sexpr_s2p_pre_list(_Fn, _, STERM, STERM) :-
% If `STERM` is not a list, return it unchanged.
\+ is_list(STERM), !.
% sexpr_s2p_pre_list(Fn, _, [S|STERM], [S|STERM]) :- STERM == [], !.
% (Commented-out clause for empty lists, may have been used for list termination.)
sexpr_s2p_pre_list(Fn, Nth, [S0|STERM0], [S|STERM]) :-
% Recursively process the list: if `S0` is a list, convert it using `sexpr_s2p/4`; otherwise, recurse.
(is_list(S0) -> sexpr_s2p(Fn, Nth, S0, S) ; sexpr_s2p_pre_list(Fn, Nth, S0, S)),
% Process the tail of the list recursively.
sexpr_s2p_pre_list(Fn, Nth, STERM0, STERM), !.
sexpr_s2p_pre_list(_Fn, _, STERM, STERM). % Fallback: return `STERM` unchanged.
%
%%%%%%%%%%%%%%%%%%%% START P2m clauses %%%%%%%%%%%
%
% p2m/2 is a translation utility to convert Prolog constructs to MeTTa constructs.
% It handles a variety of cases, including different types of compound terms,
% control structures, and predicate definitions.
% The first argument is the input in Prolog syntax,
% and the second argument is the output converted to MeTTa syntax.
%! p2m(+I) is det.
%
% A utility predicate to translate Prolog predicates (`I`) into MeTTa constructs.
% It retrieves all clauses for the given predicate, processes them, and writes
% the translated result in MeTTa syntax.
%
%
% @arg I The input predicate name in Prolog syntax to be converted.
%
% @example
% ?- p2m(my_predicate).
% This would translate the clauses of `my_predicate/Arity` into MeTTa syntax.
p2m(I):-forall(
no_repeats(current_predicate(I/A)),
(functor(P,I,A),
forall(clause(P,Body),
(numbervars(P+Body,0,_,[]),
write_src(=(P,'call!'(Body))))))).
%! p2m(+I, -O) is det.
%
% Translates Prolog predicates (`I`) into MeTTa constructs, outputting the result in `O`.
% It uses an initial context, `[progn]`, for the translation process.
%
% @arg I The input predicate name in Prolog syntax.
% @arg O The output converted into MeTTa syntax.
%
% @example
% ?- p2m(my_predicate, Output).
% Output will contain the MeTTa translation of `my_predicate`.
p2m(I, O) :-
% Initiate translation of `I` to `O` with the starting context `[progn]`.
p2m([progn], I, O).
%! p2m(+OC, +NC, -O) is det.
%
% Translates Prolog constructs (`NC`) into MeTTa constructs (`O`), using an optional context (`OC`).
% Handles a variety of Prolog terms, lists, and control structures.
%
% @arg OC The context for translation, often involving specific translation rules.
% @arg NC The input term in Prolog syntax.
% @arg O The output term converted into MeTTa syntax.
%
% @example
% ?- p2m(_, my_predicate, Output).
% Output will contain the MeTTa translation of `my_predicate`.
p2m(_OC, NC, NC) :-
% If NC is a variable, do not translate.
var(NC), !.
p2m(_OC, NC, NC) :-
% If NC is a free term variable, do not translate.
is_ftVar(NC), !.
p2m(OC, [H|T], '::'(L)) :-
% If NC is a list, map each element of the list from Prolog to MeTTa.
is_list([H|T]), maplist(p2m(OC), [H|T], L).
p2m(OC, [H|T], 'Cons'(OH, OT)) :-
% Translate a list to MeTTa 'Cons' structure.
p2m(OC, H, OH), p2m(OC, T, OT).
p2m(_OC, A, A) :-
% Conversion for any atomic term.
string(A), !.
p2m(_OC, [], 'Nil'). % Empty list is translated to 'Nil'.
p2m(_OC, '[|]', 'Cons'). % Translate '[|]' operator to 'Cons'.
p2m(_OC, !, ['set-det']). % Translate the cut operation.
p2m(_OC,!, '!'). % Translate the cut operation directly.
p2m(_OC, false, 'False'). % Translate Prolog's false to MeTTa's False.
p2m(_OC, true, 'True'). % Translate Prolog's true to MeTTa's True.
p2m([progn|_], Atom, [O]) :-
% Translate atoms using hyphenated format.
atom(Atom), !, p2m([arg], Atom, O), !.
p2m(_OC, (';'), 'xor'). % Translate ';' (or) to 'xor'.
p2m(_OC, (','), 'and2'). % Translate ',' (and) to 'and2'.
p2m(_OC, '=..', 'atom_2_list'). % Translate '=..' (univ operator) to 'atom_2_list'.
p2m([progn|_], (fail), [empty]). % Translate Prolog's fail to MeTTa's empty (False).
p2m(_OC, 'atom', 'is-symbol'). % Translate 'atom' predicate to 'is-symbol'.
p2m(_OC, 'atomic', 'symbolic'). % Translate 'atomic' to 'symbolic'.
p2m(OC, ASymbolProc, O) :-
% Translate atoms with '$' or '%' concatenation into hyphenated format.
atom(ASymbolProc),symbolic_list_concat(LS,'$',ASymbolProc),LS\==[],LS\=[_],!,
symbolic_list_concat(LS,'%',SymbolProc),into_hyphens(SymbolProc,O).
p2m(OC,ASymbolProc,O):- atom(ASymbolProc),into_hyphens(ASymbolProc,O).
p2m(_, A, H) :-
% Translate any atomic symbol into hyphenated format.
atom(A), into_hyphens(A, H), !.
p2m(_OC,A, A):- atomic(A).
p2m(_OC, NC, NC) :-
% If NC is not a compound term, return it unchanged.
\+ compound(NC), !.
p2m(_OC, NC, [F]) :-
% If NC is a functor with arity 0, convert it to a list.
compound_name_arity(NC, F, 0), !.
p2m(OC, M:I, O) :-
% Skip module qualifier if it is 'user'.
M == user, !, p2m(OC, I, O),!.
p2m(_OC, M:I, 'scoped'(N, O)) :-
% Translate a module-scoped term.
p2m(OC, M, N), p2m(I, O).
p2m(OC, NC, OO) :-
% If NC is a list, map each element of the list from Prolog to MeTTa
is_list(NC),!,
maplist(p2m(OC), NC, OO).
p2m([progn|_], (!,fail), [empty]). % Translate Prolog?s fail to MeTTa?s False.
% p2m(_OC,fail, 'False'). % Translate Prolog?s fail to MeTTa?s False.
% p2m(_OC,prolog, meTTa). % Translate the atom prolog to meTTa.
p2m([progn|_],A, [H]):-
atom(A),into_hyphens(A,H),!.
p2m(_OC, (\+ A), O) :-
% Translate negation as failure (\+ A).
!, p2m(_OC, naf(A), O).
p2m(OC, (G, E), O) :-
% Translate conjunctions (G, E).
conjuncts_to_list((G, E), List), !, into_sequential(OC, List, O), !.
p2m(_OC,(Head:-Body),O):-
Body == true,!, O = (=(Head,'True')).
p2m(_OC,(Head:-Body),O):-
Body == fail,!, O = (=(Head,[empty])).
p2m(OC,(Head:-Body),O):-
p2m(Head,H),conjuncts_to_list(Body,List),maplist(p2m([progn|OC]),List,SP),!,
O = ['=',H|SP].
p2m(OC, (:- Body), O) :-
% Translate directives (:- Body).
!, conjuncts_to_list(Body, List), into_sequential([progn|OC], List, SP), !, O = exec(SP).
p2m(OC, (? - Body), O) :-
% Translate queries (? - Body).
!, conjuncts_to_list(Body, List), into_sequential([progn|OC], List, SP), !, O = exec('?-'(SP)).
p2m(OC, (A->B;C), O) :-
% Translate if-then-else (A -> B ; C).
!, p2m(OC, det_if_then_else(A, B, C), O).
p2m(OC, (A;B), O) :-
% Translate disjunction (A ; B).
!, p2m(OC, or(A, B), O).
p2m(OC,(A*->B;C),O):-
!, p2m(OC,if(A,B,C),O).
p2m(OC,(A->B),O):-
!, p2m(OC,det_if_then(A,B),O).
p2m(OC,(A*->B),O):-
!, p2m(OC,if(A,B),O).
% Translate common Prolog database operations and metta constructs to MeTTa equivalents.
% This includes adding atoms, retrieving types and atoms, and handling assertions and retractions.
p2m(_OC,metta_defn(Eq,Self,H,B),'add-atom'(Self,[Eq,H,B])).
p2m(_OC,metta_type,'get-type').
p2m(_OC,metta_atom,'get-atoms').
%p2m(_OC,get_metta_atom,'get-atoms').
p2m(_OC,clause(H,B), ==([=,H,B],'get-atoms'('&self'))).
p2m(_OC,assert(X),'add-atom'('&self',X)).
p2m(_OC,assertz(X),'add-atom'('&self',X)).
p2m(_OC,asserta(X),'add-atom'('&self',X)).
p2m(_OC,retract(X),'remove-atom'('&self',X)).
p2m(_OC,retractall(X),'remove-all-atoms'('&self',X)).
% The catch-all case for the other compound terms.
%p2m(_OC,I,O):- I=..[F|II],maplist(p2m,[F|II],OO),O=..OO.
% Catch-all clause for compound terms. This rule breaks down a compound term `I` into its functor `F`
% and arguments `II`, recursively applies `p2m` on each argument, and then reconstructs the term
% in MeTTa format, converting the functor `F` into a hyphenated form.
p2m(OC,I, O):-
compound(I),
I =.. [F|II], % univ operator to convert between a term and a list consisting of functor name and arguments
maplist(p2m([F|OC]), II, OO), % applying p2m recursively on each argument of the compound term
into_hyphens(F,FF),
O = [FF|OO]. % constructing the output term with the converted arguments
%
%%%%%%%%%%%%%%%%%%%% END P2m clauses %%%%%%%%%%%
%
% In the context of this conversion predicate, each branch of the p2m predicate
% is handling a different type or structure of term, translating it into its
% equivalent representation in another logic programming language named MeTTa.
% The actual transformations are dependent on the correspondence between Prolog
% constructs and MeTTa constructs, as defined by the specific implementations
% of Prolog and MeTTa being used.
%! prolog_to_metta(+PrologTerm, -MeTTaTerm) is det.
%
% Translates a given Prolog term into its corresponding representation in MeTTa.
% This conversion is dependent on the structure of the Prolog term and its
% mapping to MeTTa constructs. The transformation rules are governed by the
% relationship between Prolog and MeTTa, a different logic programming language.
%
% @arg PrologTerm The Prolog term that is to be converted.
% @arg MeTTaTerm The resulting term in MeTTa after the translation.
%
% @example Translating a Prolog term to MeTTa:
% ?- prolog_to_metta(some_prolog_term, MeTTaRepresentation).
% MeTTaRepresentation = corresponding_metta_term.
%
prolog_to_metta(V, D) :-
% Calls the internal p2m predicate to perform the actual translation.
% The [progn] list element may signify the starting construct or context
% for the MeTTa language.
p2m([progn], V, D), !.
%! into_sequential(+Context, +Body, -MeTTaRepresentation) is det.
%
% Transforms a Prolog term that represents a conjunction of terms into a sequential
% representation in MeTTa syntax. The predicate handles cases where the body is a
% conjunction, converting it into a MeTTa-friendly list, or if it is a single term,
% directly translating it using `prolog_to_metta/2`.
%
% @arg Context The context for the MeTTa transformation (e.g., [progn] to signify sequential execution).
% @arg Body The Prolog term to be transformed. This can be a conjunction, a list of terms, or a single term.
% @arg MeTTaRepresentation The resulting representation in MeTTa.
%
% @example Converting a conjunction of terms into a sequential MeTTa list:
% ?- into_sequential([progn], (term1, term2), MeTTaList).
% MeTTaList = ['progn', MeTTaTerm1, MeTTaTerm2].
%
into_sequential(OC, Body, SP) :-
% Check if Body is not already a list, then convert conjunctions into a list of conjuncts.
\+ is_list(Body),
conjuncts_to_list(Body, List),
% Ensure the resulting List is a valid list and recursively process it into sequential MeTTa representation.
is_list(List),
into_sequential(OC, List, SP), !.
into_sequential([progn|_], Nothing, 'True') :-
% Handle the case where Body is empty (Nothing) by returning 'True' in MeTTa.
Nothing == [], !.
% Handle the case where Body is empty (Nothing) by returning 'Nil' in MeTTa.
into_sequential(_OC, Nothing, 'Nil') :-
Nothing == [], !.
into_sequential(_, [SP], O) :-
% If there is only one element, directly translate it using `prolog_to_metta/2`.
prolog_to_metta(SP, O).
into_sequential([progn|_], List, SPList) :-
% Otherwise, translate the list into sequential MeTTa representation using `progn`.
maplist(prolog_to_metta, List, SPList), !.
into_sequential(_CA, List, [AND|SPList]) :-
% If AND conjunction is used, translate the list with 'AND' in MeTTa.
is_compiled_and(AND),
maplist(prolog_to_metta, List, SPList), !.
%! list_direct_subdirectories(+Directory, -DirectSubdirectories) is det.
%
% Retrieves the direct subdirectories of a given directory.
% This predicate returns a list of all subdirectories within the specified directory,
% excluding the special entries '.' and '..'.
%
% @arg Directory The directory path whose direct subdirectories are to be listed.
% @arg DirectSubdirectories A list of paths corresponding to the direct subdirectories
% of the given Directory.
%
% @example Listing direct subdirectories of '/home/user':
% ?- list_direct_subdirectories('/home/user', Subdirs).
% Subdirs = ['/home/user/dir1', '/home/user/dir2'].
%
list_direct_subdirectories(Directory, DirectSubdirectories) :-
% Retrieve all files and directories in the given Directory.
directory_files(Directory, Entries),
% Find all subdirectories, excluding '.' and '..'.
findall(Path,
(member(Entry, Entries),
\+ member(Entry, ['.', '..']), % Exclude special entries '.' and '..'
symbolic_list_concat([Directory, '/', Entry], Path),
is_directory(Path)),
DirectSubdirectories).
%! list_all_subdirectories(+Directory, -AllSubdirectories) is det.
%
% Recursively lists all subdirectories of a given directory. This predicate
% traverses the directory structure and accumulates both direct and nested
% subdirectories, returning them as a flat list.
%
% @arg Directory The directory whose subdirectories (including nested ones) are to be listed.
% @arg AllSubdirectories A list of paths corresponding to all subdirectories of the given Directory, recursively.
%
% @example Listing all subdirectories recursively from '/home/user':
% ?- list_all_subdirectories('/home/user', Subdirs).
% Subdirs = ['/home/user/dir1', '/home/user/dir2', '/home/user/dir1/subdir1', ...].
%