-
Notifications
You must be signed in to change notification settings - Fork 0
/
fn.go
749 lines (656 loc) · 16.7 KB
/
fn.go
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
package trit
import (
"context"
"math/rand"
"reflect"
"runtime"
"sync"
"time"
)
var (
// The parallelTasks the number of parallel tasks.
parallelTasks = 1
// The maxParallelTasks is the maximum number of parallel tasks.
maxParallelTasks = runtime.NumCPU() * 3
// The minLoadPerGoroutine is the minimum slice size for processing
// in an individual goroutine. Essentially, it delineates the threshold
// at which it becomes worthwhile to divide the slice processing amongst
// multiple goroutines. If each goroutine isn't handling a sufficiently
// large subslice, the overhead of goroutine creation and management
// may outweigh the benefits of concurrent processing. This variable
// specifies the minimum number of iterations per goroutine to ensure
// an efficient division of labor.
minLoadPerGoroutine = 1024
// This line asserts at compile time that the type *Trit
// implements the Tritter interface.
_ Tritter = (*Trit)(nil)
)
// Logicable is a special data type from which to determine the state of Trit
// in the context of three-valued logic.
type Logicable interface {
bool | Trit |
int | int8 | int16 | int32 | int64 |
uint | uint8 | uint16 | uint32 | uint64 |
float32 | float64
}
// Tritter is a special data type that implements the Trit interface.
type Tritter interface {
IsTrue() bool
IsFalse() bool
IsUnknown() bool
Int() int
String() string
}
// The logicFoundValue is a helper struct that holds a boolean value
// and a Mutex to protect it from concurrent access.
//
// They are used in the In function to detect the desired result
// in a separate goroutine.
type logicFoundValue struct {
m sync.Mutex
value Trit
}
// SetValue sets a new value for the Found. It locks the Mutex before
// changing the value and unlocks it after the change is complete.
func (f *logicFoundValue) SetValue(value Trit) {
f.m.Lock()
defer f.m.Unlock()
f.value = value
}
// GetValue retrieves the current value of the Found. It locks the Mutex
// before reading the value and unlocks it after the read is complete.
func (f *logicFoundValue) GetValue() Trit {
f.m.Lock()
defer f.m.Unlock()
return f.value
}
// The init initializes the randomGenerator variable.
func init() {
parallelTasks = runtime.NumCPU() * 2
}
// ParallelTasks returns the number of parallel tasks.
//
// If the function is called without parameters, it returns the
// current value of parallelTasks.
//
// A function can receive one or more values for parallelTasks,
// these values are added together to form the final result for
// parallelTasks. If the new value for parallelTasks is less than
// or equal to zero - it will be set to 1, if it is greater than
// maxParallelTasks - it will be set to maxParallelTasks.
func ParallelTasks(v ...int) int {
if len(v) > 0 {
n := 0
for _, value := range v {
n += value
}
if n <= 0 {
parallelTasks = 1
} else if n > maxParallelTasks {
parallelTasks = maxParallelTasks
} else {
parallelTasks = n
}
}
return parallelTasks
}
// The logicToTrit function converts any logic type to Trit.
func logicToTrit[T Logicable](v T) Trit {
switch any(v).(type) {
case bool:
if any(v).(bool) {
return True
}
return False
case int, int8, int16, int32, int64:
switch reflect.TypeOf(v).Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
value := reflect.ValueOf(v).Int()
if value > 0 {
return True
} else if value < 0 {
return False
}
return Unknown
}
case uint, uint8, uint16, uint32, uint64:
switch reflect.TypeOf(v).Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64:
value := reflect.ValueOf(v).Uint()
if value > 0 {
return True
}
// Can't be less than 0
return Unknown
}
case float32, float64:
switch reflect.TypeOf(v).Kind() {
case reflect.Float32, reflect.Float64:
value := reflect.ValueOf(v).Float()
if value > 0 {
return True
} else if value < 0 {
return False
}
return Unknown
}
}
return any(v).(Trit)
}
// Default sets the default value for the trit-object
// if this one has a Unknown state.
//
// Example usage:
//
// t := trit.Unknown
// trit.Default(&t, trit.True)
// fmt.Println(t.String()) // Output: True
func Default[T Logicable](t *Trit, v T) Trit {
// If the trit is not Unknown, return the trit.
if t.Val() != Unknown {
return *t
}
trit := logicToTrit(v)
*t = trit
return *t
}
// IsFalse checks if the trit-object is False.
//
// See Trit.IsFalse() for more information.
func IsFalse[T Logicable](t T) bool {
trit := logicToTrit(t)
return trit.IsFalse()
}
// IsUnknown checks if the trit-object is Unknown.
//
// See Trit.IsUnknown() for more information.
func IsUnknown[T Logicable](t T) bool {
trit := logicToTrit(t)
return trit.IsUnknown()
}
// IsTrue checks if the trit-object is True.
//
// See Trit.IsTrue() for more information.
func IsTrue[T Logicable](t T) bool {
trit := logicToTrit(t)
return trit.IsTrue()
}
// Set sets the value of the trit-object.
//
// See Trit.Set() for more information.
func Set[T Logicable](t *Trit, v T) Trit {
trit := logicToTrit(v)
*t = trit
return *t
}
// Convert converts the any Logicable types to Trit.
//
// Example usage:
//
// tuf := trit.Convert(true, 0, -1)
// fmt.Println(tuf[0].String()) // Output: True
// fmt.Println(tuf[1].String()) // Output: Unknown
// fmt.Println(tuf[2].String()) // Output: False
func Convert[T Logicable](v ...T) []Trit {
trit := make([]Trit, len(v))
for i, value := range v {
trit[i] = logicToTrit(value)
}
return trit
}
// Define converts the any Logicable type to Trit.
//
// Example usage:
//
// t := trit.Define(true)
// fmt.Println(t.String()) // Output: True
func Define[T Logicable](v T) Trit {
trit := logicToTrit(v)
return trit
}
// All returns True if all the trit-objects are True.
//
// Example usage:
//
// t := trit.All(trit.True, trit.True, trit.True)
// fmt.Println(t.String()) // Output: True
func All[T Logicable](t ...T) Trit {
var wg sync.WaitGroup
// Will use context to stop the rest of the goroutines
// if the value has already been found.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p := parallelTasks
found := &logicFoundValue{value: True}
// If the length of the slice is less than or equal to
// the minLoadPerGoroutine, then we do not need
// to use goroutines.
if l := len(t); l == 0 {
return False
} else if l/p < minLoadPerGoroutine {
for _, v := range t {
trit := logicToTrit(v)
if trit.IsFalse() || trit.IsUnknown() {
return False
}
}
return True
}
chunkSize := len(t) / p
for i := 0; i < p; i++ {
wg.Add(1)
start := i * chunkSize
end := start + chunkSize
if i == p-1 {
end = len(t)
}
go func(start, end int) {
defer wg.Done()
for _, b := range t[start:end] {
trit := logicToTrit(b)
// Check if the context has been cancelled.
select {
case <-ctx.Done():
return
default:
}
if trit.IsFalse() || trit.IsUnknown() {
found.SetValue(False)
cancel() // stop all other goroutines
return
}
}
}(start, end)
}
wg.Wait()
return found.GetValue()
}
// Any returns True if any of the trit-objects are True.
//
// Example usage:
//
// t := trit.Any(trit.True, trit.False, trit.False)
// fmt.Println(t.String()) // Output: True
func Any[T Logicable](t ...T) Trit {
var wg sync.WaitGroup
// Will use context to stop the rest of the goroutines
// if the value has already been found.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p := parallelTasks
found := &logicFoundValue{value: False}
// If the length of the slice is less than or equal to
// the minLoadPerGoroutine, then we do not need
// to use goroutines.
if l := len(t); l == 0 {
return False
} else if l/p < minLoadPerGoroutine {
for _, v := range t {
trit := logicToTrit(v)
if trit.IsTrue() {
return True
}
}
return False
}
chunkSize := len(t) / p
for i := 0; i < p; i++ {
wg.Add(1)
start := i * chunkSize
end := start + chunkSize
if i == p-1 {
end = len(t)
}
go func(start, end int) {
defer wg.Done()
for _, b := range t[start:end] {
trit := logicToTrit(b)
// Check if the context has been cancelled.
select {
case <-ctx.Done():
return
default:
}
if trit.IsTrue() {
found.SetValue(True)
cancel() // stop all other goroutines
return
}
}
}(start, end)
}
wg.Wait()
return found.GetValue()
}
// None returns True if none of the trit-objects are True.
//
// Example usage:
//
// t := trit.None(trit.False, trit.False, trit.False)
// fmt.Println(t.String()) // Output: True
func None[T Logicable](t ...T) Trit {
for _, v := range t {
trit := logicToTrit(v)
if trit.IsTrue() {
return False
}
}
return True
}
// Not performs a logical NOT operation on a Trit-Like value and
// returns the result as Trit.
//
// See Trit.Not() for more information.
func Not[T Logicable](t T) Trit {
trit := logicToTrit(t)
return trit.Not()
}
// Ma performs a logical MA (Modus Ponens Absorption) operation
// on a Trit-Like values and returns the result as Trit.
//
// See Trit.Ma() for more information.
func Ma[T Logicable](t T) Trit {
trit := logicToTrit(t)
return trit.Ma()
}
// La performs a logical LA (Law of Absorption) operation on a Trit-Like
// value and returns the result as Trit.
//
// See Trit.La() for more information.
func La[T Logicable](t T) Trit {
trit := logicToTrit(t)
return trit.La()
}
// Ia performs a logical IA (Idempotent Absorption) operation on a Trit-Like
// value and returns the result as Trit.
//
// See Trit.Ia() for more information.
func Ia[T Logicable](t T) Trit {
trit := logicToTrit(t)
return trit.Ia()
}
// And performs a logical AND operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.And() for more information.
func And[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.And(tb)
}
// Or performs a logical OR operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Or() for more information.
func Or[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Or(tb)
}
// Xor performs a logical XOR operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Xor() for more information.
func Xor[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Xor(tb)
}
// Nand performs a logical NAND operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Nand() for more information.
func Nand[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Nand(tb)
}
// Nor performs a logical NOR operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Nor() for more information.
func Nor[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Nor(tb)
}
// Nxor performs a logical NXOR operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Nxor() for more information.
func Nxor[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Nxor(tb)
}
// Min performs a logical MIN operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Min() for more information.
func Min[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Min(tb)
}
// Max performs a logical MAX operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Max() for more information.
func Max[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Max(tb)
}
// Imp performs a logical IMP operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Imp() for more information.
func Imp[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Imp(tb)
}
// Nimp performs a logical NIMP operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Nimp() for more information.
func Nimp[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Nimp(tb)
}
// Eq performs a logical EQ operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Eq() for more information.
func Eq[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Eq(tb)
}
// Neq performs a logical NEQ operation between two Trit-Like values
// and returns the result as Trit.
//
// See Trit.Neq() for more information.
func Neq[T, U Logicable](a T, b U) Trit {
ta := logicToTrit(a)
tb := logicToTrit(b)
return ta.Neq(tb)
}
// Known returns boolean true if all Trit-Like values has definiteness,
// i.e. is either True or False.
//
// Example usage:
//
// a := trit.Known(trit.True, trit.False, trit.Unknown)
// fmt.Println(a.String()) // Output: False
//
// b := trit.Known(trit.True, trit.True, trit.False)
// fmt.Println(b.String()) // Output: True
func Known[T Logicable](ts ...T) Trit {
var wg sync.WaitGroup
// Will use context to stop the rest of the goroutines
// if the value has already been found.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p := parallelTasks
found := &logicFoundValue{value: True}
// If the length of the slice is less than or equal to
// the minLoadPerGoroutine, then we do not need
// to use goroutines.
if l := len(ts); l == 0 {
return False
} else if l/p < minLoadPerGoroutine {
for _, t := range ts {
trit := logicToTrit(t)
if trit == Unknown {
return False
}
}
return True
}
chunkSize := len(ts) / p
for i := 0; i < p; i++ {
wg.Add(1)
start := i * chunkSize
end := start + chunkSize
if i == p-1 {
end = len(ts)
}
go func(start, end int) {
defer wg.Done()
for _, b := range ts[start:end] {
trit := logicToTrit(b)
// Check if the context has been cancelled.
select {
case <-ctx.Done():
return
default:
}
if trit.IsUnknown() {
found.SetValue(False)
cancel() // stop all other goroutines
return
}
}
}(start, end)
}
wg.Wait()
return found.GetValue()
}
// IsConfidence returns boolean true if all Trit-Like values has definiteness,
// i.e. is either True or False.
//
// Example usage:
//
// a := trit.IsConfidence(trit.True, trit.False, trit.Unknown)
// fmt.Println(a.String()) // Output: False
//
// b := trit.IsConfidence(trit.True, trit.True, trit.False)
// fmt.Println(b.String()) // Output: True
func IsConfidence[T Logicable](ts ...T) bool {
for _, t := range ts {
trit := logicToTrit(t)
if trit == Unknown {
return false
}
}
return true
}
// Random returns a random Trit value.
// The function can accept an optional argument that indicates the
// percentage probability of the occurrence of the Unknown event.
//
// Example usage:
//
// a := trit.Random()
// fmt.Println(a.String()) // Output: True, False or Unknown
//
// b := trit.Random(0)
// fmt.Println(b.String()) // Output: True or False
//
// c := trit.Random(50)
// fmt.Println(c.String()) // Output: With a probability of 50% is Unknown
func Random(up ...uint8) Trit {
// Determination of the probability of occurrence of the event Unknown.
var p int
if len(up) == 0 {
p = 33
} else {
for _, v := range up {
p += int(v)
}
}
if p > 100 {
p = 100
}
// Generate random value.
rand.Seed(time.Now().UnixNano())
value := rand.Intn(100)
if value < p {
return Unknown
}
if value < (100-p)/2 {
return True
}
return False
}
// Consensus returns True if all input trits are True, False if all are False,
// and Unknown otherwise.
//
// Example usage:
//
// t1, t2, t3 := trit.True, trit.True, trit.Unknown
// result := Consensus(t1, t2, t3)
// // result will be Unknown, as not all trits are the same
func Consensus[T Logicable](trits ...T) Trit {
countT := 0
countF := 0
for _, x := range trits {
trit := logicToTrit(x)
switch trit.Val() {
case True:
countT++
case False:
countF++
default:
return Unknown
}
}
if countT == len(trits) {
return True
} else if countF == len(trits) {
return False
}
return Unknown
}
// Majority returns True if more than half of the input trits are True, False
// if more than half are False, and Unknown otherwise.
//
// Example usage:
//
// t1, t2, t3, t4 := trit.True, trit.True, trit.False, trit.Unknown
// result := Majority(t1, t2, t3, t4)
// // result will be True, as more than half of the trits are True
func Majority[T Logicable](trits ...T) Trit {
countT := 0
countF := 0
for _, x := range trits {
trit := logicToTrit(x)
switch trit.Val() {
case True:
countT++
case False:
countF++
}
}
if countT > len(trits)/2 {
return True
} else if countF > len(trits)/2 {
return False
} else {
return Unknown
}
}