-
Notifications
You must be signed in to change notification settings - Fork 32
/
elements.py
4741 lines (3928 loc) · 131 KB
/
elements.py
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
"""This is where the element functions are stored
(that is, functions directly corresponding to Vyxal elements). It's also where
the python equivalent of command is stored
"""
import itertools
import math
import random
import re
import string
import types
from datetime import datetime
from typing import Union
import num2words
import numpy
import sympy
from vyxal import dictionary
from vyxal.context import DEFAULT_CTX, Context
from vyxal.encoding import (
base_27_alphabet,
codepage_number_compress,
codepage_string_compress,
)
from vyxal.helpers import *
from vyxal.LazyList import LazyList, lazylist
currentdate = datetime.now()
NUMBER_TYPE = "number"
SCALAR_TYPE = "scalar"
EPSILON = 1e-10
def process_element(
expr: Union[str, types.FunctionType], arity: int
) -> tuple[str, int]:
"""Take a python expression and adds boilerplate for element functions to it
expr can be a string, which will be added verbatim to the transpiled output,
or a function, for which a function call will be generated.
See documents/specs/Transpilation.md for information on what happens here.
"""
if arity:
arguments = ["third", "rhs", "lhs"][-arity:]
else:
arguments = "_"
if isinstance(expr, types.FunctionType):
pushed = f"{expr.__name__}({', '.join(arguments[::-1])}, ctx=ctx)"
else:
pushed = expr
py_code = (
f"{', '.join(arguments)} = pop(stack, {arity}, ctx); "
f"stack.append({pushed})"
)
return py_code, arity
def absolute_difference(lhs, rhs, ctx):
"""Element ε
(num, num) -> abs(a - b)
(any, str) -> Transpose a (filling with b), join on newlines
"""
ts = vy_type(lhs, rhs)
if ts == (NUMBER_TYPE, NUMBER_TYPE):
return abs(lhs - rhs)
else:
return vertical_join(lhs, rhs, ctx)
def add(lhs, rhs, ctx):
"""Element +
(num, num) -> lhs + rhs
(num, str) -> str(lhs) + rhs
(str, num) -> lhs + str(rhs)
(str, str) -> lhs + rhs
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: lhs + rhs,
(NUMBER_TYPE, str): lambda: str(lhs) + rhs,
(str, NUMBER_TYPE): lambda: lhs + str(rhs),
(str, str): lambda: lhs + rhs,
}.get(ts, lambda: vectorise(add, lhs, rhs, ctx=ctx))()
def all_combos(lhs, ctx):
"""Element Þx
(any) -> all combinations without replacement of lhs (all lengths)
"""
all_without_replacement = map(
lambda x: itertools.combinations(lhs, x), range(1, len(lhs) + 1)
)
@lazylist
def gen():
for combo in all_without_replacement:
for item in combo:
for x in itertools.permutations(item):
if all(isinstance(y, str) for y in x):
x = "".join(x)
yield vyxalify(x)
return gen()
def all_combos_with_replacement(lhs, ctx):
"""Element Þ×
(any) -> all combinations with replacement of lhs (all lengths)
"""
all_with_replacement = map(
lambda x: itertools.combinations_with_replacement(lhs, x),
range(1, len(lhs) + 1),
)
@lazylist
def gen():
for combo in all_with_replacement:
for x in combo:
if all(isinstance(y, str) for y in x):
x = "".join(x)
yield vyxalify(x)
return gen()
def all_diagonals(lhs, ctx):
"""Element ÞD
Diagonals of a matrix, starting with the main diagonal.
"""
@lazylist
def gen():
vector = list(map(lambda x: iterable(x, ctx=ctx), lhs))
diag_num = 0
diagonal = numpy.diag(vector)
# postive diags first
while len(diagonal):
yield vyxalify(diagonal)
diag_num += 1
diagonal = numpy.diag(vector, k=diag_num)
diag_num = -1
diagonal = numpy.diag(vector, k=diag_num)
# now the other diagonals
while len(diagonal):
yield vyxalify(diagonal)
diag_num -= 1
diagonal = numpy.diag(vector, k=diag_num)
return gen()
def all_equal(lhs, ctx):
"""Element ≈
(any) -> are all items in a the same?
"""
lhs = iterable(lhs, ctx=ctx)
if len(lhs) == 0:
return 1
else:
first = lhs[0]
for item in lhs[1:]:
if not non_vectorising_equals(item, first, ctx):
return 0
return 1
def all_less_than_increasing(lhs, rhs, ctx):
"""Element Þ<
(any, num): All values of a up to (not including) the first greater
than or equal to b
"""
lhs = iterable(lhs, ctx)
@lazylist
def gen():
for elem in lhs:
if elem < rhs:
yield elem
else:
return
return gen()
def all_partitions(lhs, ctx):
"""Element øṖ
(any) -> all_partitions(a)
"""
lhs = iterable(lhs, ctx=ctx)
@lazylist
def gen():
shapes = integer_parts_or_join_spaces(len(lhs), ctx)
yield from (wrap(lhs, shape, ctx) for shape in shapes)
return gen()
def all_true(lhs, ctx):
"""Element A
(lst) -> all of lhs is truthy?
(str) -> is_vowel (vectorises over multichar strings)
"""
if isinstance(lhs, str):
if len(lhs) == 1:
return int(lhs in "aeiouAEIOU")
else:
return [int(char in "aeiouAEIOU") for char in lhs]
return int(all(iterable(lhs, ctx)))
def all_unique(lhs, ctx):
"""Element Þu
(any) -> Are all elements of a unique?
"""
return int(len(uniquify(lhs, ctx)) == len(iterable(lhs, ctx=ctx)))
def angle_bracketify(lhs, ctx):
"""Element øḂ
(any) -> "<" + lhs + ">"
(lst) -> vectorised
"""
if vy_type(lhs, simple=True) is list:
return vectorise(angle_bracketify, lhs)
return "<" + str(lhs) + ">"
def anti_diagonal(lhs, ctx):
lhs = numpy.asarray(iterable(lhs, ctx=ctx))
lhs = numpy.fliplr(lhs)
return vyxalify(lhs.diagonal())
def any_true(lhs, ctx):
"""Element a
(lst) -> any of lhs is truthy?
(str) -> is_capital_letter (vectorises over multichar strings)
"""
if isinstance(lhs, str):
if len(lhs) == 1:
return int(91 >= ord(lhs) >= 65)
else:
return [int(91 >= ord(char) >= 65) for char in lhs]
return int(any(iterable(lhs, ctx=ctx)))
def apply_at(lhs, rhs, other, ctx):
"""Element ¨M
(lst, lst, fun) -> Map a function to elements of a list whose
indices are in another list
"""
lhs = iterable(lhs, ctx=ctx)
rhs = wrapify(rhs)
for pos in rhs:
lhs = assign_iterable(
lhs, pos, safe_apply(other, index(lhs, pos, ctx), ctx=ctx), ctx
)
return lhs
def arccos(lhs, ctx):
"""Element ∆C
(num) -> arccos(lhs)
"""
ts = vy_type(lhs)
return {
(NUMBER_TYPE): lambda: sympy.nsimplify(sympy.acos(lhs)),
(str): lambda: sympy.nsimplify(sympy.acos(make_expression(lhs))),
}.get(ts, lambda: vectorise(arccos, lhs, ctx=ctx))()
def arcsin(lhs, ctx):
"""Element ∆S
(num) -> arcsin(a)
"""
ts = vy_type(lhs)
return {
(NUMBER_TYPE): lambda: sympy.nsimplify(sympy.asin(lhs)),
(str): lambda: sympy.nsimplify(sympy.asin(make_expression(lhs))),
}.get(ts, lambda: vectorise(arcsin, lhs, ctx=ctx))()
def arctan(lhs, ctx):
"""Element ∆T
(num) -> arctan(a)
"""
ts = vy_type(lhs)
return {
(NUMBER_TYPE): lambda: sympy.nsimplify(sympy.atan(lhs)),
(str): lambda: sympy.nsimplify(sympy.atan(make_expression(lhs))),
}.get(ts, lambda: vectorise(arctan, lhs, ctx=ctx))()
def assign_iterable(lhs, rhs, other, ctx):
"""Element Ȧ
(any, num, any) -> a but item b (0-indexed) is set to c
"""
lhs = iterable(lhs, ctx=ctx)
if type(rhs) is str:
rhs = chr_ord(rhs, ctx)
if vy_type(rhs, simple=True) is list:
for item in rhs:
lhs = assign_iterable(lhs, item, other, ctx)
return lhs
if type(lhs) is str:
lhs = list(lhs)
lhs[rhs] = other
return vy_sum(lhs, ctx=ctx)
else:
lhs[rhs] = other
return lhs
def base_255_string_compress(lhs, ctx):
"""Element øc
(str) -> Compress a string of lowercase letters and spaces in base 255
"""
return (
"«"
+ to_base(
from_base(lhs, base_27_alphabet, ctx),
codepage_string_compress,
ctx,
)
+ "«"
)
def base_255_number_compress(lhs, ctx):
"""Element øC
(num) -> Compress a number in base 255
"""
return "»" + to_base(lhs, codepage_number_compress, ctx) + "»"
def bitwise_and(lhs, rhs, ctx):
"""Element ⋏
(num, num) -> a & b
(num, str) -> b.center(a)
(str, num) -> a.center(b)
(str, str) -> a.center(len(b) - len(a))
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: lhs & rhs,
(NUMBER_TYPE, str): lambda: rhs.center(lhs),
(str, NUMBER_TYPE): lambda: lhs.center(rhs),
(str, str): lambda: lhs.center(abs(len(rhs) - len(lhs))),
}.get(ts, lambda: vectorise(bitwise_and, lhs, rhs, ctx=ctx))()
def bitwise_or(lhs, rhs, ctx):
"""Element ⋎
(num, num) -> a | b
(num, str) -> b[:a]+b[a+1:]
(str, num) -> a[:b]+a[b+1:]
(str, str) -> merge_join(a,b)
"""
ts = vy_type(lhs, rhs)
if ts == (str, str):
suffixes = {lhs[-i:] for i in range(1, len(lhs) + 1)}
prefixes = {rhs[:i] for i in range(1, len(rhs) + 1)}
common = suffixes & prefixes
if len(common) == 0:
return lhs + rhs
common = sorted(common, key=lambda x: len(x))[-1]
return lhs[: -len(common)] + common + rhs[len(common) :]
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: lhs | rhs,
(NUMBER_TYPE, str): lambda: rhs[:lhs] + rhs[lhs + 1 :],
(str, NUMBER_TYPE): lambda: lhs[:rhs] + lhs[rhs + 1 :],
}.get(ts, lambda: vectorise(bitwise_or, lhs, rhs, ctx=ctx))()
def bitwise_not(lhs, ctx):
"""Element ꜝ
(num) -> ~a
(str) -> any_upper(a)
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: ~lhs,
str: lambda: int(any(char.isupper() for char in lhs)),
}.get(ts, lambda: vectorise(bitwise_not, lhs, ctx=ctx))()
def bitwise_xor(lhs, rhs, ctx):
"""Element ꘍
(num, num) -> a ^ b
(num, str) -> " " * a + b
(str, num) -> a + " " * b
(str, str) -> levenshtein_distance(a,b)
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: lhs ^ rhs,
(NUMBER_TYPE, str): lambda: " " * lhs + rhs,
(str, NUMBER_TYPE): lambda: lhs + " " * rhs,
(str, str): lambda: levenshtein_distance(lhs, rhs),
}.get(ts, lambda: vectorise(bitwise_xor, lhs, rhs, ctx=ctx))()
def boolify(lhs, ctx):
"""Element ḃ
(any) -> is truthy?
"""
if vy_type(lhs, simple=True) is list:
if ctx.truthy_lists:
return any_true(lhs, ctx)
else:
return vectorise(boolify, lhs, ctx=ctx)
else:
return int(bool(lhs))
def bracketify(lhs, ctx):
"""Element øB
(any) -> "[" + lhs + "]"
(lst) -> vectorised
"""
if vy_type(lhs, simple=True) is list:
return vectorise(bracketify, lhs)
return "[" + str(lhs) + "]"
def brackets_balanced(lhs, ctx):
"""Element øβ
(str) -> is lhs balanced?
"""
brackets = {"(": ")", "[": "]", "{": "}", "<": ">"}
temp = []
for char in lhs:
if char in brackets.keys():
temp.append(brackets[char])
elif char in brackets.values():
if temp and temp[-1] != char:
return 0
elif not temp:
return 0
else:
temp.pop()
return int(len(temp) == 0)
def cartesian_power(lhs, rhs, ctx):
"""Element ÞẊ
(any, num) -> cartesian_power(a, b)
(num, any) -> cartesian_power(b, a)
"""
ts = vy_type(lhs, rhs)
if NUMBER_TYPE not in ts:
return rhs
else:
lhs, rhs = (lhs, rhs) if ts[-1] == NUMBER_TYPE else (rhs, lhs)
return LazyList(
"".join(x) if all(isinstance(y, str) for y in x) else x
for x in itertools.product(iterable(lhs, ctx=ctx), repeat=int(rhs))
)
def cartesian_product(lhs, rhs, ctx):
"""Element Ẋ
(any, any) -> cartesian product of lhs and rhs
"""
return LazyList(
left + right
if isinstance(left, str) and isinstance(right, str)
else [left, right]
for left in iterable(lhs, range, ctx=ctx)
for right in iterable(rhs, range, ctx=ctx)
)
def center(lhs, ctx):
"""Element øc
(list) -> center align list by padding with spaces
"""
focal = max(map(lambda x: len(iterable(x, ctx=ctx)), lhs))
return [line.center(focal) for line in lhs]
def chr_ord(lhs, ctx):
"""Element C
(num) -> chr(a)
(str) -> ord(a)
"""
ts = vy_type(lhs)
return {
(NUMBER_TYPE): lambda: chr(int(lhs)),
(str): lambda: list(map(ord, lhs)) if len(lhs) > 1 else ord(lhs),
}.get(ts, lambda: vectorise(chr_ord, lhs, ctx=ctx))()
def combinations_with_replacement(lhs, rhs, ctx):
"""Element ↔
(any, num) -> combinations of lhs of length rhs with replacement
(any, non-num) -> remove elements in lhs that are not in rhs
(fun, any) -> apply lhs on rhs until the result does not change. Collects intermediate values
(any, fun) -> apply rhs on lhs until the result does not change. Collects intermediate values
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, ts[1]): lambda: vyxalify(
itertools.product(iterable(rhs, ctx), repeat=lhs)
),
(ts[0], NUMBER_TYPE): lambda: vyxalify(
itertools.product(iterable(lhs, ctx), repeat=rhs)
),
(types.FunctionType, ts[1]): lambda: fixed_point(lhs, rhs),
(ts[0], types.FunctionType): lambda: fixed_point(rhs, lhs),
}.get(ts, lambda: keep(lhs, rhs))()
def complement(lhs, ctx):
"""Element ⌐
(num) -> 1 - a
(str) -> a.split(",")
"""
ts = vy_type(lhs)
return {NUMBER_TYPE: lambda: 1 - lhs, str: lambda: lhs.split(",")}.get(
ts, lambda: vectorise(complement, lhs, ctx=ctx)
)()
def contains(lhs, rhs, ctx):
"""Element c
(any, any) -> count of a in b
"""
lhs = iterable(lhs, ctx=ctx)
for item in lhs:
if item == rhs:
return 1
return 0
def coords_deepmap(lhs, rhs, ctx):
"""Element ÞZ
(any, fun) -> For each value of a (all the way down) call b with the
coordinates of that value and put that at the
appropriate position in a.
Or, as hyper said: for each value of a, call b with the coordinates
of that value is just deepmap(b, multidimindex(a))
https://chat.stackexchange.com/transcript/message/59662626#59662626
"""
lhs, rhs = (lhs, rhs) if type(rhs) is types.FunctionType else (rhs, lhs)
# arrange so that lhs is always the list and rhs is always the
# function
lhs = iterable(lhs, ctx=ctx) # Make sure lhs is actually iterable
f = lambda a, g, pos=(): [
f(b, g, (*pos, i))
if isinstance(b, list)
else safe_apply(g, [*pos, i], ctx=ctx)
for i, b in enumerate(a)
]
# the above curtosey of pxeger
# https://chat.stackexchange.com/transcript/message/59662694#59662694
# thank you very cool
return f(lhs, rhs)
def copy_sign(lhs, rhs, ctx):
"""Element ∆±
(num, num) -> math.copysign(a, b)
"""
return multiply(
vy_abs(lhs, ctx), (-1 if less_than(rhs, 0, ctx) else 1), ctx
)
def cosine(lhs, ctx):
"""Element ∆c
(num) -> cosine(a)
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: sympy.nsimplify(sympy.cos(lhs)),
str: lambda: sympy.nsimplify(sympy.cos(make_expression(lhs))),
}.get(ts, lambda: vectorise(cosine, lhs, ctx=ctx))()
def count(lhs, rhs, ctx):
"""Element O
(any, any) -> returns the number of occurances of b in a
"""
return iterable(lhs, ctx=ctx).count(rhs)
def counts(lhs, ctx):
temp = uniquify(lhs, ctx=ctx)
return [[x, count(lhs, x, ctx)] for x in temp]
def cumulative_sum(lhs, ctx):
"""Element ¦
(any) -> cumulative sum of a
"""
return LazyList(scanl(add, iterable(lhs, ctx=ctx), ctx))
def curly_bracketify(lhs, ctx):
"""Element øḃ
(any) -> "[" + lhs + "]"
(lst) -> vectorised
"""
if vy_type(lhs, simple=True) is list:
return vectorise(curly_bracketify, lhs)
return "{" + str(lhs) + "}"
def custom_pad_left(lhs, rhs, other, ctx):
"""Element ø↲
(any, num, str) -> pad a on the left with c to length b
(any, str, num) -> pad a on the left with b to length c
(lst, any, any) -> vectorised
"""
if isinstance(lhs, LazyList):
return vectorise(custom_pad_left, lhs, rhs, other)
if isinstance(rhs, int):
return lhs.ljust(rhs, other)
if isinstance(other, int):
return lhs.ljust(other, rhs)
def custom_pad_right(lhs, rhs, other, ctx):
"""Element ø↳
(any, num, str) -> pad a on the right with c to length b
(any, str, num) -> pad a on the right with b to length c
(lst, any, any) -> vectorised
"""
if isinstance(lhs, LazyList):
return vectorise(custom_pad_left, lhs, rhs, other)
if isinstance(rhs, int):
return lhs.rjust(rhs, other)
if isinstance(other, int):
return lhs.rjust(other, rhs)
def decrement(lhs, ctx):
"""Element ‹
(num) -> a - 1
(str) -> a + "-"
"""
ts = vy_type(lhs)
return {NUMBER_TYPE: lambda: lhs - 1, str: lambda: lhs + "-"}.get(
ts, lambda: vectorise(decrement, lhs, ctx=ctx)
)()
def deep_flatten(lhs, ctx):
"""Element f
(any) -> flatten list
"""
ret = []
for item in iterable(lhs, ctx=ctx):
if type(item) in (LazyList, list):
ret += deep_flatten(item, ctx)
else:
ret.append(item)
return ret
def deltas(lhs, ctx):
"""Element ¯
(any) -> deltas of a
"""
lhs = iterable(lhs, ctx=ctx)
return LazyList(
subtract(lhs[i + 1], lhs[i], ctx=ctx) for i in range(len(lhs) - 1)
)
def diagonal(lhs, ctx):
"""Element Þ/
(any) -> diagonal of a
"""
lhs = numpy.asarray(iterable(lhs, ctx=ctx))
return vyxalify(lhs.diagonal())
def divide(lhs, rhs, ctx):
"""Element /
(num, num) -> a / b
(num, str) -> b split into a even length pieces, possibly with an extra part
(str, num) -> a split into b even length pieces, possibly with an extra part
(str, str) -> split a on b
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: 0
if lhs == rhs == 0
else vyxalify(sympy.nsimplify(lhs / rhs)),
(NUMBER_TYPE, str): lambda: wrap(rhs, len(rhs) // lhs, ctx),
(str, NUMBER_TYPE): lambda: wrap(lhs, len(lhs) // rhs, ctx),
(str, str): lambda: lhs.split(rhs),
}.get(ts, lambda: vectorise(divide, lhs, rhs, ctx=ctx))()
def divisors(lhs, ctx):
"""Element K
(num) -> divisors(a) # Factors or divisors of a
(str) -> all substrings of a that occur more than once
(lst) -> prefixes(a) # Prefixes of a
"""
ts = vy_type(lhs)
if ts == NUMBER_TYPE:
return sympy.divisors(lhs)
elif ts == str:
return uniquify(
LazyList(
filter(
lambda substr: lhs.count(substr) > 1,
substrings(lhs, ctx),
)
),
ctx,
)
return LazyList((lhs[: x + 1] for x in range(len(lhs))))
def divisor_sum(lhs, ctx):
"""Element ∆K
(num) -> sum of proper divisors of a
"""
return vy_sum(divisors(lhs, ctx)[:-1], ctx)
def dot_product(lhs, rhs, ctx):
"""Element Þ•
Return the dot product of lhs and rhs
"""
return vy_sum(multiply(lhs, rhs, ctx), ctx)
def dyadic_maximum(lhs, rhs, ctx):
"""Element ∴
(any, any) -> max(a, b)
"""
return lhs if greater_than(lhs, rhs, ctx) else rhs
def dyadic_minimum(lhs, rhs, ctx):
"""Element ∵
(any, any) -> min(a, b)
"""
return lhs if less_than(lhs, rhs, ctx) else rhs
def e_digits(lhs, ctx):
"""Element ∆Ė
(int) -> e_digits(a)
"""
if vy_type(lhs) == NUMBER_TYPE:
estr = str(sympy.N(sympy.E, int(lhs) + 1))
estr = estr[0] + estr[2:-1]
return LazyList(map(int, estr))
else:
return vectorise(e_digits, lhs, ctx=ctx)
def equals(lhs, rhs, ctx):
"""Element =
(num, num) -> lhs == rhs
(num, str) -> str(lhs) == rhs
(str, num) -> lhs == str(rhs)
(str, str) -> lhs == rhs
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: int(
bool(
abs(simplify(lhs - rhs)) < EPSILON
or abs(simplify(lhs - rhs)) < EPSILON * abs(lhs)
)
),
(NUMBER_TYPE, str): lambda: int(str(lhs) == rhs),
(str, NUMBER_TYPE): lambda: int(lhs == str(rhs)),
(str, str): lambda: int(lhs == rhs),
}.get(ts, lambda: vectorise(equals, lhs, rhs, ctx=ctx))()
def euclidean_distance(lhs, rhs, ctx):
"""Element ∆d
(num, num) -> distance between a and b
"""
return square_root(
vy_sum(exponent(subtract(lhs, rhs, ctx), 2, ctx), ctx), ctx
)
def evenly_distribute(lhs, rhs, ctx):
"""Element Þ…
(list, num) -> Evenly distribute a over all elements of b,
adding each part
"""
lhs = iterable(lhs, ctx=ctx)
if not lhs:
return lhs
each = rhs // len(lhs)
extra = rhs - each * len(lhs)
if isinstance(lhs, list):
return [
lhs[i] + each + 1 if i < extra else lhs[i] + each
for i in range(len(lhs))
]
@lazylist
def gen():
i = 0
for elem in lhs:
if i < extra:
yield elem + each + 1
else:
yield elem + each
i += 1
return gen()
def exclusive_one_range(lhs, ctx):
"""Element ɽ
(num) -> range(1, a)
(str) -> a.lower()
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: LazyList(range(1, int(lhs))),
str: lambda: lhs.lower(),
}.get(ts, lambda: vectorise(exclusive_one_range, lhs, ctx=ctx))()
def exclusive_zero_range(lhs, ctx):
"""Element ʁ
(num) -> range(0, a)
(str) -> mirror(a)
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: LazyList(range(0, int(lhs))),
str: lambda: merge(lhs, reverse(lhs, ctx)[1:], ctx),
}.get(ts, lambda: vectorise(exclusive_zero_range, lhs, ctx=ctx))()
def exp2_or_eval(lhs, ctx):
"""Element E
(num) -> 2 ** a
(str) -> eval(a)
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: 2 ** lhs,
str: lambda: vy_eval(lhs, ctx),
}.get(ts, lambda: vectorise(exp2_or_eval, lhs, ctx=ctx))()
def expe(lhs, ctx):
"""Element ∆e
(num) -> e ** a
(str) -> simplify expression a
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: sympy.exp(lhs),
str: lambda: str(sympy.simplify(make_expression(lhs))),
}.get(ts, lambda: vectorise(expe, lhs, ctx=ctx))()
def expe_minus_1(lhs, ctx):
"""Element ∆E
(num) -> (e ** a) - 1
(str) -> expand expression a
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: sympy.exp(lhs) - 1,
str: lambda: str(sympy.expand(make_expression(lhs))),
}.get(ts, lambda: vectorise(expe_minus_1, lhs, ctx=ctx))()
def exponent(lhs, rhs, ctx):
"""Element e
(num, num) -> a ** b (exponentiation)
(num, str) -> append b[0] to b until b is length a (spaces if b is empty)
(str, num) -> append a[0] to a until a is length b (spaces if a is empty)
(str, str) -> regex.search(pattern=a, string=b).span() (Length of regex match)
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: lhs ** rhs,
(NUMBER_TYPE, str): lambda: rhs
+ ((rhs[0] or " ") * (int(lhs) - len(rhs))),
(str, NUMBER_TYPE): lambda: lhs
+ ((lhs[0] or " ") * (int(rhs) - len(lhs))),
(str, str): lambda: list(re.search(lhs, rhs).span()),
}.get(ts, lambda: vectorise(exponent, lhs, rhs, ctx=ctx))()
def factorial(lhs, ctx):
"""Element ¡
(num) -> factorial(a) (math.gamma(a + 1))
(str) -> a.sentence_case()
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: vyxalify(sympy.factorial(abs(lhs))),
# Because otherwise, it returns a very unhelpful factorial obj
str: lambda: sentence_case(lhs),
}.get(ts, lambda: vectorise(factorial, lhs, ctx=ctx))()
def factorials(_, ctx):
"""Element Þ!
An infinite lazylist of factorials
"""
@lazylist
def gen():
i = 0
while True:
yield factorial(i, ctx)
i += 1
return gen()
def factorial_of_range(lhs, ctx):
"""Element øF
(num, num) -> factorial of range
(num, str) -> vectorised
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: math.factorial(lhs),
str: lambda: vectorise(factorial_of_range, lhs, ctx=ctx),
}.get(ts, lambda: vectorise(factorial_of_range, lhs, ctx=ctx))()
def fibonaacis(_, ctx):
"""Element ÞF
An infinite lazylist of fibonaaci numbers
"""
@lazylist
def gen():
i = 0