forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.0.diff
More file actions
2256 lines (2150 loc) · 83.1 KB
/
2.0.diff
File metadata and controls
2256 lines (2150 loc) · 83.1 KB
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
diff --git a/fp-anamorphisms.ts b/fp-anamorphisms.ts
index 3b609afa26..cec345c177 100644
--- a/fp-anamorphisms.ts
+++ b/fp-anamorphisms.ts
@@ -377,9 +377,9 @@ export function validationResultCoalg(seed: number): Result<number, string> | nu
if (seed < 0) {
return null; // Terminate for negative numbers
} else if (seed > 100) {
- return Result.Err(`Value too large: ${seed}`);
+ return Err(`Value too large: ${seed}`);
} else {
- return Result.Ok(seed);
+ return Ok(seed);
}
}
diff --git a/fp-catamorphisms.ts b/fp-catamorphisms.ts
index 02ab0a0d22..05e70db4b4 100644
--- a/fp-catamorphisms.ts
+++ b/fp-catamorphisms.ts
@@ -512,8 +512,8 @@ export function exampleExprFold(): void {
* Example: Using fold with Result
*/
export function exampleResultFold(): void {
- const success = Result.Ok(42);
- const failure = Result.Err('Something went wrong');
+ const success = Ok(42);
+ const failure = Err('Something went wrong');
const successAlgebra = resultSuccessAlgebra<number, string>(
error => parseInt(error) || 0
diff --git a/fp-gadt-enhanced.ts b/fp-gadt-enhanced.ts
index 1e151321b8..86c4a1bc4e 100644
--- a/fp-gadt-enhanced.ts
+++ b/fp-gadt-enhanced.ts
@@ -436,8 +436,8 @@ export const resultMatcher = createPmatchBuilder<Result<any, any>, string>({
export const ResultFunctor: Functor<ResultK> = {
map: <A, B>(fa: Result<A, any>, f: (a: A) => B): Result<B, any> =>
pmatch(fa)
- .with('Ok', ({ value }) => Result.Ok(f(value)))
- .with('Err', ({ error }) => Result.Err(error))
+ .with('Ok', ({ value }) => Ok(f(value)))
+ .with('Err', ({ error }) => Err(error))
.exhaustive()
};
@@ -445,11 +445,11 @@ export const ResultFunctor: Functor<ResultK> = {
* Derive Monad from minimal definitions
*/
export function deriveResultMonad(): Monad<ResultK> {
- const of = <A>(a: A): Result<A, any> => Result.Ok(a);
+ const of = <A>(a: A): Result<A, any> => Ok(a);
const chain = <A, B>(fa: Result<A, any>, f: (a: A) => Result<B, any>): Result<B, any> =>
pmatch(fa)
.with('Ok', ({ value }) => f(value))
- .with('Err', ({ error }) => Result.Err(error))
+ .with('Err', ({ error }) => Err(error))
.exhaustive();
return deriveMonad<ResultK>(of, chain);
@@ -552,8 +552,8 @@ export function exampleExprFunctor(): void {
* Example: Derivable Instances + Auto-Matchers on Result
*/
export function exampleResultIntegration(): void {
- const success = Result.Ok(42);
- const failure = Result.Err('Something went wrong');
+ const success = Ok(42);
+ const failure = Err('Something went wrong');
// Use auto-generated matcher
const successResult = resultMatcher(success).exhaustive();
@@ -567,7 +567,7 @@ export function exampleResultIntegration(): void {
const chained = derivedMonad.chain(
success,
- x => x > 40 ? Result.Ok(x * 2) : Result.Err('Too small')
+ x => x > 40 ? Ok(x * 2) : Err('Too small')
);
const chainedResult = resultMatcher(chained).exhaustive();
diff --git a/fp-hylomorphisms.ts b/fp-hylomorphisms.ts
index 9312b462be..497f4c366f 100644
--- a/fp-hylomorphisms.ts
+++ b/fp-hylomorphisms.ts
@@ -409,11 +409,11 @@ export function processResultHylo(seed: number): string {
// Unfold coalgebra: generate Result from seed
const generateCoalgebra = (s: number): Result<number, string> => {
if (s < 0) {
- return Result.Err('Negative number');
+ return Err('Negative number');
} else if (s > 100) {
- return Result.Err('Too large');
+ return Err('Too large');
} else {
- return Result.Ok(s);
+ return Ok(s);
}
};
@@ -507,13 +507,13 @@ export function createValidationHylo(): (value: number) => string {
// Unfold coalgebra: generate validation result
const validationCoalgebra = (value: number): Result<number, string> => {
if (value < 0) {
- return Result.Err('Negative value');
+ return Err('Negative value');
} else if (value > 100) {
- return Result.Err('Value too large');
+ return Err('Value too large');
} else if (value === 0) {
- return Result.Err('Zero is not allowed');
+ return Err('Zero is not allowed');
} else {
- return Result.Ok(value);
+ return Ok(value);
}
};
diff --git a/fp-immutable.ts b/fp-immutable.ts
index 90603daf45..80c88f6240 100644
--- a/fp-immutable.ts
+++ b/fp-immutable.ts
@@ -1,11 +1,17 @@
/**
- * Immutable Core - Type-safe Immutability Utilities
+ * Structural Immutability Utilities
*
- * This module provides:
- * - Type-level immutability utilities (shallow and deep)
- * - Runtime helpers for safe updates to immutable data
- * - Integration with the FP ecosystem (typeclasses, HKTs, GADTs)
- * - Structural sharing for efficient immutable operations
+ * This module provides comprehensive immutability utilities for arrays, objects, and tuples
+ * with type-level tracking so the Purity System can detect and propagate immutability guarantees.
+ *
+ * Features:
+ * - Core type-level definitions (Immutable<T>, DeepReadonly<T>, IsImmutable<T>)
+ * - Immutable constructors for arrays, objects, and tuples
+ * - Safe update utilities that never mutate
+ * - Integration with purity system (defaults to Pure)
+ * - Typeclass integration (ImmutableFunctor, ImmutableMonad)
+ * - Readonly pattern matching support
+ * - Compile-time immutability enforcement
*/
import {
@@ -16,942 +22,767 @@ import {
} from './fp-hkt';
import {
- Functor, Applicative, Monad, Bifunctor,
+ Functor, Applicative, Monad, Bifunctor, Profunctor, Traversable, Foldable,
deriveFunctor, deriveApplicative, deriveMonad,
lift2, composeK, sequence, traverse
} from './fp-typeclasses-hkt';
import {
- GADT, GADTTags, GADTPayload,
- pmatch, PatternMatcherBuilder,
- derivePatternMatcher, createPmatchBuilder,
- Expr, ExprK, evaluate, transformString, ExprFunctor,
- MaybeGADT, MaybeGADTK, MaybeGADTFunctor, MaybeGADTApplicative, MaybeGADTMonad,
- EitherGADT, EitherGADTK, EitherGADTBifunctor,
- Result, ResultK, ResultFunctor, deriveResultMonad
-} from './fp-gadt-enhanced';
+ EffectTag, EffectOf, Pure, IO, Async, Effect,
+ isPure, isIO, isAsync, getEffectTag,
+ PurityContext, PurityError, PurityResult,
+ createPurityInfo, attachPurityMarker, extractPurityMarker, hasPurityMarker
+} from './fp-purity';
// ============================================================================
-// Part 1: Type-Level Immutability Utilities
+// Part 1: Core Type-Level Definitions
// ============================================================================
/**
- * Shallow structural immutability
- * Makes all properties readonly at the top level
+ * Recursively marks all fields as readonly, ensuring array/tuple elements are immutable too
+ *
+ * @example
+ * ```typescript
+ * type ImmutableUser = Immutable<{
+ * name: string;
+ * age: number;
+ * hobbies: string[];
+ * address: { city: string; country: string; }
+ * }>;
+ *
+ * // Results in:
+ * // {
+ * // readonly name: string;
+ * // readonly age: number;
+ * // readonly hobbies: readonly string[];
+ * // readonly address: {
+ * // readonly city: string;
+ * // readonly country: string;
+ * // };
+ * // }
+ * ```
+ */
+export type Immutable<T> = T extends readonly (infer U)[]
+ ? readonly Immutable<U>[]
+ : T extends readonly [...infer Head, ...infer Tail]
+ ? readonly [...Immutable<Head>, ...Immutable<Tail>]
+ : T extends readonly [infer First, ...infer Rest]
+ ? readonly [Immutable<First>, ...Immutable<Rest>]
+ : T extends readonly []
+ ? readonly []
+ : T extends (infer U)[]
+ ? readonly Immutable<U>[]
+ : T extends [...infer Head, ...infer Tail]
+ ? readonly [...Immutable<Head>, ...Immutable<Tail>]
+ : T extends [infer First, ...infer Rest]
+ ? readonly [Immutable<First>, ...Immutable<Rest>]
+ : T extends []
+ ? readonly []
+ : T extends object
+ ? { readonly [K in keyof T]: Immutable<T[K]> }
+ : T;
+
+/**
+ * Synonym for Immutable<T>, but keeps naming consistent with TS style
+ */
+export type DeepReadonly<T> = Immutable<T>;
+
+/**
+ * Resolves to true if T is Immutable, false otherwise
+ *
+ * @example
+ * ```typescript
+ * type Check1 = IsImmutable<readonly number[]>; // true
+ * type Check2 = IsImmutable<number[]>; // false
+ * type Check3 = IsImmutable<{ readonly a: number }>; // true
+ * type Check4 = IsImmutable<{ a: number }>; // false
+ * ```
*/
-export type Immutable<T> = { readonly [K in keyof T]: T[K] };
+export type IsImmutable<T> = T extends Immutable<T> ? true : false;
/**
- * Deep structural immutability
- * Recursively makes all properties readonly throughout the object structure
+ * Phantom kind to tag an HKT as producing immutable structures
*/
-export type DeepImmutable<T> =
- T extends (infer U)[] ? readonly DeepImmutable<U>[] :
- T extends readonly (infer U)[] ? readonly DeepImmutable<U>[] :
- T extends Set<infer U> ? ReadonlySet<DeepImmutable<U>> :
- T extends Map<infer K, infer V> ? ReadonlyMap<DeepImmutable<K>, DeepImmutable<V>> :
- T extends object ? { readonly [K in keyof T]: DeepImmutable<T[K]> } :
- T;
+export interface ImmutableKind<T> {
+ readonly __immutableBrand: unique symbol;
+ readonly type: Immutable<T>;
+}
/**
- * Immutable tuple that retains tuple-ness
- * Preserves the exact length and structure of the original tuple
+ * Branded type for immutable values with runtime immutability guarantee
*/
-export type ImmutableTuple<T extends readonly unknown[]> = { readonly [K in keyof T]: DeepImmutable<T[K]> };
+export interface ImmutableBrand {
+ readonly __immutableBrand: unique symbol;
+}
/**
- * Mutable type (removes readonly modifiers)
- * Inverse of Immutable<T>
+ * Type that combines immutability with a branded guarantee
*/
-export type Mutable<T> = { -readonly [K in keyof T]: T[K] };
+export type ImmutableValue<T> = Immutable<T> & ImmutableBrand;
/**
- * Deep mutable type (removes readonly modifiers recursively)
- * Inverse of DeepImmutable<T>
+ * Check if a type is an immutable value (branded)
*/
-export type DeepMutable<T> =
- T extends readonly (infer U)[] ? DeepMutable<U>[] :
- T extends ReadonlySet<infer U> ? Set<DeepMutable<U>> :
- T extends ReadonlyMap<infer K, infer V> ? Map<DeepMutable<K>, DeepMutable<V>> :
- T extends object ? { -readonly [K in keyof T]: DeepMutable<T[K]> } :
- T;
+export type IsImmutableValue<T> = T extends ImmutableBrand ? true : false;
/**
- * Conditional immutability
- * Makes T immutable if Condition is true, otherwise leaves it mutable
+ * Extract the underlying type from an immutable value
*/
-export type ConditionalImmutable<T, Condition extends boolean> =
- Condition extends true ? DeepImmutable<T> : T;
+export type ExtractImmutableType<T> = T extends ImmutableValue<infer U> ? U : T;
+
+// ============================================================================
+// Part 2: Integration with Purity System
+// ============================================================================
/**
- * Immutable array type
- * Preserves array methods while ensuring immutability
+ * Extend the purity system to recognize immutable types as Pure
*/
-export type ImmutableArray<T> = readonly DeepImmutable<T>[];
+declare module './fp-purity' {
+ interface EffectKind<Tag extends EffectTag> {
+ readonly __immutableBrand?: ImmutableBrand;
+ }
+}
/**
- * Immutable object with optional properties
- * Makes all properties readonly and optional
+ * Immutable type with purity integration
*/
-export type ImmutablePartial<T> = { readonly [K in keyof T]?: DeepImmutable<T[K]> };
+export interface ImmutableWithPurity<T, P extends EffectTag = 'Pure'> {
+ readonly value: Immutable<T>;
+ readonly effect: P;
+ readonly __immutableBrand: ImmutableBrand;
+}
/**
- * Immutable object with required properties
- * Makes all properties readonly and required
+ * Create an immutable value with purity information
*/
-export type ImmutableRequired<T> = { readonly [K in keyof T]-?: DeepImmutable<T[K]> };
+export function createImmutableWithPurity<T, P extends EffectTag = 'Pure'>(
+ value: T,
+ effect: P = 'Pure' as P
+): ImmutableWithPurity<T, P> {
+ const immutableValue = deepFreeze(value) as Immutable<T>;
+ return {
+ value: immutableValue,
+ effect,
+ __immutableBrand: {} as ImmutableBrand
+ };
+}
/**
- * Immutable record type
- * Creates an immutable object with keys of type K and values of type V
+ * Extract the effect from an immutable value
*/
-export type ImmutableRecord<K extends string | number | symbol, V> = { readonly [P in K]: DeepImmutable<V> };
-
-// ============================================================================
-// Part 2: Runtime Helpers for Safe Updates
-// ============================================================================
+export type EffectOfImmutable<T> = T extends ImmutableWithPurity<any, infer P> ? P : 'Pure';
/**
- * Deep freeze an object, making it immutable at runtime
- * @param obj - The object to freeze
- * @returns The deeply frozen object
+ * Check if an immutable value is pure
*/
-export function freezeDeep<T>(obj: T): DeepImmutable<T> {
- if (obj === null || obj === undefined || typeof obj !== 'object') {
- return obj as DeepImmutable<T>;
- }
-
- if (Array.isArray(obj)) {
- return Object.freeze(obj.map(item => freezeDeep(item))) as DeepImmutable<T>;
- }
-
- if (obj instanceof Set) {
- return Object.freeze(new Set(Array.from(obj).map(item => freezeDeep(item)))) as DeepImmutable<T>;
- }
+export type IsImmutablePure<T> = EffectOfImmutable<T> extends 'Pure' ? true : false;
- if (obj instanceof Map) {
- return Object.freeze(new Map(
- Array.from(obj.entries()).map(([key, value]) => [freezeDeep(key), freezeDeep(value)])
- )) as DeepImmutable<T>;
- }
+// ============================================================================
+// Part 3: Immutable Constructors
+// ============================================================================
- const frozen = {} as DeepImmutable<T>;
- for (const key in obj) {
- if (obj.hasOwnProperty(key)) {
- (frozen as any)[key] = freezeDeep((obj as any)[key]);
- }
- }
- return Object.freeze(frozen);
+/**
+ * Create an immutable array with type safety
+ *
+ * @example
+ * ```typescript
+ * const nums = immutableArray(1, 2, 3);
+ * // Type: readonly number[]
+ * // No mutation methods like push, pop are available
+ * ```
+ */
+export function immutableArray<T>(...items: Immutable<T>[]): Immutable<T[]> {
+ return Object.freeze([...items]) as Immutable<T[]>;
}
/**
- * Update an immutable object by applying an updater function to a specific key
- * @param obj - The immutable object to update
- * @param key - The key to update
- * @param updater - Function that takes the current value and returns the new value
- * @returns A new immutable object with the updated value
- */
-export function updateImmutable<T, K extends keyof T>(
- obj: T,
- key: K,
- updater: (value: T[K]) => T[K]
-): T {
- const newObj = { ...obj } as T;
- (newObj as any)[key] = updater((obj as any)[key]);
- return newObj;
+ * Create an immutable tuple with type inference
+ *
+ * @example
+ * ```typescript
+ * const tuple = immutableTuple(1, "hello", true);
+ * // Type: readonly [number, string, boolean]
+ * ```
+ */
+export function immutableTuple<T extends readonly any[]>(
+ ...items: { [K in keyof T]: Immutable<T[K]> }
+): Immutable<T> {
+ return Object.freeze([...items]) as Immutable<T>;
}
/**
- * Set a value at a specific path in an immutable object
- * @param obj - The immutable object to update
- * @param path - Array of keys representing the path to the value
- * @param value - The new value to set
- * @returns A new immutable object with the updated value
- */
-export function setInImmutable<T>(obj: T, path: (string | number)[], value: unknown): T {
- if (path.length === 0) {
- return value as T;
- }
-
- const [first, ...rest] = path;
-
- if (Array.isArray(obj)) {
- const index = Number(first);
- const newArray = [...obj] as any[];
- newArray[index] = rest.length === 0 ? value : setInImmutable(newArray[index], rest, value);
- return newArray as T;
- }
-
- if (typeof obj === 'object' && obj !== null) {
- const newObj = { ...obj } as any;
- newObj[first] = rest.length === 0 ? value : setInImmutable(newObj[first], rest, value);
- return newObj as T;
- }
-
- throw new Error(`Cannot set value at path ${path.join('.')} in non-object/non-array`);
+ * Create an immutable object with deep freezing
+ *
+ * @example
+ * ```typescript
+ * const obj = immutableObject({ a: 1, b: { c: 2 } });
+ * // Type: { readonly a: number; readonly b: { readonly c: number; } }
+ * ```
+ */
+export function immutableObject<T extends object>(obj: T): Immutable<T> {
+ return deepFreeze(obj) as Immutable<T>;
}
/**
- * Push items to an immutable array
- * @param arr - The immutable array
- * @param items - Items to push
- * @returns A new immutable array with the items added
- */
-export function pushImmutable<T>(arr: readonly T[], ...items: T[]): readonly T[] {
- return [...arr, ...items];
+ * Create an immutable set
+ *
+ * @example
+ * ```typescript
+ * const set = immutableSet(1, 2, 3);
+ * // Type: ReadonlySet<number>
+ * ```
+ */
+export function immutableSet<T>(...items: Immutable<T>[]): ReadonlySet<Immutable<T>> {
+ return Object.freeze(new Set(items)) as ReadonlySet<Immutable<T>>;
}
/**
- * Splice an immutable array (remove and/or insert items)
- * @param arr - The immutable array
- * @param start - Starting index
- * @param deleteCount - Number of items to delete
- * @param items - Items to insert
- * @returns A new immutable array with the changes applied
- */
-export function spliceImmutable<T>(
- arr: readonly T[],
- start: number,
- deleteCount: number = 0,
- ...items: T[]
-): readonly T[] {
- const newArray = [...arr];
- newArray.splice(start, deleteCount, ...items);
- return newArray;
+ * Create an immutable map
+ *
+ * @example
+ * ```typescript
+ * const map = immutableMap([["a", 1], ["b", 2]]);
+ * // Type: ReadonlyMap<string, number>
+ * ```
+ */
+export function immutableMap<K, V>(
+ entries: readonly (readonly [Immutable<K>, Immutable<V>])[]
+): ReadonlyMap<Immutable<K>, Immutable<V>> {
+ return Object.freeze(new Map(entries)) as ReadonlyMap<Immutable<K>, Immutable<V>>;
}
+// ============================================================================
+// Part 4: Safe Update Utilities
+// ============================================================================
+
/**
* Update an immutable array at a specific index
- * @param arr - The immutable array
- * @param index - The index to update
- * @param updater - Function that takes the current value and returns the new value
- * @returns A new immutable array with the updated value
- */
-export function updateArrayImmutable<T>(
- arr: readonly T[],
+ * Always returns a new array - never mutates
+ *
+ * @example
+ * ```typescript
+ * const nums = immutableArray(1, 2, 3);
+ * const updated = updateImmutableArray(nums, 1, 42);
+ * // updated: readonly [number, number, number]
+ * // nums remains unchanged
+ * ```
+ */
+export function updateImmutableArray<T>(
+ arr: Immutable<T[]>,
index: number,
- updater: (value: T) => T
-): readonly T[] {
+ value: Immutable<T>
+): Immutable<T[]> {
if (index < 0 || index >= arr.length) {
throw new Error(`Index ${index} out of bounds for array of length ${arr.length}`);
}
const newArray = [...arr];
- newArray[index] = updater(newArray[index]);
- return newArray;
+ newArray[index] = value;
+ return Object.freeze(newArray) as Immutable<T[]>;
}
/**
- * Remove an item from an immutable array at a specific index
- * @param arr - The immutable array
- * @param index - The index to remove
- * @returns A new immutable array without the item at the specified index
- */
-export function removeFromImmutable<T>(arr: readonly T[], index: number): readonly T[] {
- return spliceImmutable(arr, index, 1);
+ * Update an immutable object at a specific key
+ * Always returns a new object - never mutates
+ *
+ * @example
+ * ```typescript
+ * const obj = immutableObject({ a: 1, b: 2 });
+ * const updated = updateImmutableObject(obj, 'a', 42);
+ * // updated: { readonly a: number; readonly b: number }
+ * // obj remains unchanged
+ * ```
+ */
+export function updateImmutableObject<T extends object, K extends keyof T>(
+ obj: Immutable<T>,
+ key: K,
+ value: Immutable<T[K]>
+): Immutable<T> {
+ return Object.freeze({
+ ...obj,
+ [key]: value
+ }) as Immutable<T>;
}
/**
- * Insert an item into an immutable array at a specific index
- * @param arr - The immutable array
- * @param index - The index to insert at
- * @param item - The item to insert
- * @returns A new immutable array with the item inserted
- */
-export function insertImmutable<T>(arr: readonly T[], index: number, item: T): readonly T[] {
- return spliceImmutable(arr, index, 0, item);
+ * Update an immutable tuple at a specific index
+ * Always returns a new tuple - never mutates
+ *
+ * @example
+ * ```typescript
+ * const tuple = immutableTuple(1, "hello", true);
+ * const updated = updateImmutableTuple(tuple, 1, "world");
+ * // updated: readonly [number, string, boolean]
+ * // tuple remains unchanged
+ * ```
+ */
+export function updateImmutableTuple<T extends readonly any[], I extends keyof T>(
+ tuple: Immutable<T>,
+ index: I,
+ value: Immutable<T[I]>
+): Immutable<T> {
+ if (index < 0 || index >= tuple.length) {
+ throw new Error(`Index ${String(index)} out of bounds for tuple of length ${tuple.length}`);
+ }
+
+ const newTuple = [...tuple] as T;
+ newTuple[index] = value;
+ return Object.freeze(newTuple) as Immutable<T>;
}
/**
- * Update an immutable set by adding or removing items
- * @param set - The immutable set
- * @param items - Items to add
- * @param itemsToRemove - Items to remove
- * @returns A new immutable set with the changes applied
- */
-export function updateSetImmutable<T>(
- set: ReadonlySet<T>,
- items: T[] = [],
- itemsToRemove: T[] = []
-): ReadonlySet<T> {
- const newSet = new Set(set);
- items.forEach(item => newSet.add(item));
- itemsToRemove.forEach(item => newSet.delete(item));
- return newSet;
+ * Deep merge two immutable objects
+ * Always returns a new object - never mutates
+ *
+ * @example
+ * ```typescript
+ * const obj1 = immutableObject({ a: 1, b: { c: 2 } });
+ * const obj2 = immutableObject({ b: { d: 3 }, e: 4 });
+ * const merged = mergeImmutableObjects(obj1, obj2);
+ * // merged: { readonly a: number; readonly b: { readonly c: number; readonly d: number; }; readonly e: number; }
+ * ```
+ */
+export function mergeImmutableObjects<T extends object, U extends object>(
+ obj1: Immutable<T>,
+ obj2: Immutable<U>
+): Immutable<T & U> {
+ const merged = { ...obj1 };
+
+ for (const [key, value] of Object.entries(obj2)) {
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
+ merged[key as keyof (T & U)] = mergeImmutableObjects(
+ merged[key as keyof (T & U)] as object,
+ value as object
+ ) as (T & U)[keyof (T & U)];
+ } else {
+ merged[key as keyof (T & U)] = value as (T & U)[keyof (T & U)];
+ }
+ }
+
+ return Object.freeze(merged) as Immutable<T & U>;
}
/**
- * Update an immutable map by setting or removing key-value pairs
- * @param map - The immutable map
- * @param entries - Key-value pairs to set
- * @param keysToRemove - Keys to remove
- * @returns A new immutable map with the changes applied
- */
-export function updateMapImmutable<K, V>(
- map: ReadonlyMap<K, V>,
- entries: [K, V][] = [],
- keysToRemove: K[] = []
-): ReadonlyMap<K, V> {
- const newMap = new Map(map);
- entries.forEach(([key, value]) => newMap.set(key, value));
- keysToRemove.forEach(key => newMap.delete(key));
- return newMap;
+ * Append to an immutable array
+ * Always returns a new array - never mutates
+ *
+ * @example
+ * ```typescript
+ * const nums = immutableArray(1, 2, 3);
+ * const appended = appendImmutableArray(nums, 4);
+ * // appended: readonly [number, number, number, number]
+ * // nums remains unchanged
+ * ```
+ */
+export function appendImmutableArray<T>(
+ arr: Immutable<T[]>,
+ item: Immutable<T>
+): Immutable<T[]> {
+ return Object.freeze([...arr, item]) as Immutable<T[]>;
}
/**
- * Merge two immutable objects
- * @param obj1 - The first immutable object
- * @param obj2 - The second immutable object
- * @returns A new immutable object with properties from both objects
- */
-export function mergeImmutable<T1, T2>(obj1: T1, obj2: T2): T1 & T2 {
- return { ...obj1, ...obj2 } as T1 & T2;
+ * Prepend to an immutable array
+ * Always returns a new array - never mutates
+ *
+ * @example
+ * ```typescript
+ * const nums = immutableArray(1, 2, 3);
+ * const prepended = prependImmutableArray(nums, 0);
+ * // prepended: readonly [number, number, number, number]
+ * // nums remains unchanged
+ * ```
+ */
+export function prependImmutableArray<T>(
+ arr: Immutable<T[]>,
+ item: Immutable<T>
+): Immutable<T[]> {
+ return Object.freeze([item, ...arr]) as Immutable<T[]>;
}
/**
- * Merge multiple immutable objects
- * @param objects - Array of immutable objects to merge
- * @returns A new immutable object with properties from all objects
- */
-export function mergeAllImmutable<T extends readonly object[]>(...objects: T): T[number] {
- return objects.reduce((acc, obj) => ({ ...acc, ...obj }), {}) as T[number];
+ * Remove an item from an immutable array by index
+ * Always returns a new array - never mutates
+ *
+ * @example
+ * ```typescript
+ * const nums = immutableArray(1, 2, 3);
+ * const removed = removeImmutableArray(nums, 1);
+ * // removed: readonly [number, number]
+ * // nums remains unchanged
+ * ```
+ */
+export function removeImmutableArray<T>(
+ arr: Immutable<T[]>,
+ index: number
+): Immutable<T[]> {
+ if (index < 0 || index >= arr.length) {
+ throw new Error(`Index ${index} out of bounds for array of length ${arr.length}`);
+ }
+
+ const newArray = [...arr];
+ newArray.splice(index, 1);
+ return Object.freeze(newArray) as Immutable<T[]>;
}
// ============================================================================
-// Part 3: FP Ecosystem Integration
+// Part 5: Deep Freeze Utility
// ============================================================================
/**
- * Immutable Array Kind for FP typeclass integration
- */
-export interface ImmutableArrayK extends Kind1 {
- readonly type: ImmutableArray<this['arg0']>;
-}
-
-/**
- * Immutable Tuple Kind for FP typeclass integration
- */
-export interface ImmutableTupleK extends Kind2 {
- readonly type: ImmutableTuple<[this['arg0'], this['arg1']]>;
+ * Deep freeze an object, making it and all nested objects immutable
+ *
+ * @example
+ * ```typescript
+ * const obj = { a: 1, b: { c: 2, d: [3, 4] } };
+ * const frozen = deepFreeze(obj);
+ * // frozen and all nested objects are now immutable
+ * ```
+ */
+export function deepFreeze<T>(obj: T): Immutable<T> {
+ if (obj === null || obj === undefined || typeof obj !== 'object') {
+ return obj as Immutable<T>;
+ }
+
+ // Freeze the object itself
+ Object.freeze(obj);
+
+ // Freeze all properties
+ for (const key of Object.getOwnPropertyNames(obj)) {
+ const value = (obj as any)[key];
+ if (value && typeof value === 'object') {
+ deepFreeze(value);
+ }
+ }
+
+ return obj as Immutable<T>;
}
/**
- * Immutable Set Kind for FP typeclass integration
- */
-export interface ImmutableSetK extends Kind1 {
- readonly type: ReadonlySet<this['arg0']>;
+ * Check if an object is deeply frozen
+ *
+ * @example
+ * ```typescript
+ * const obj = { a: 1, b: { c: 2 } };
+ * const frozen = deepFreeze(obj);
+ * const isFrozen = isDeeplyFrozen(frozen); // true
+ * ```
+ */
+export function isDeeplyFrozen<T>(obj: T): obj is Immutable<T> {
+ if (obj === null || obj === undefined || typeof obj !== 'object') {
+ return true;
+ }
+
+ if (!Object.isFrozen(obj)) {
+ return false;
+ }
+
+ for (const key of Object.getOwnPropertyNames(obj)) {
+ const value = (obj as any)[key];
+ if (value && typeof value === 'object' && !isDeeplyFrozen(value)) {
+ return false;
+ }
+ }
+
+ return true;
}
-/**
- * Immutable Map Kind for FP typeclass integration
- */
-export interface ImmutableMapK extends Kind2 {
- readonly type: ReadonlyMap<this['arg0'], this['arg1']>;
-}
+// ============================================================================
+// Part 6: Typeclass Integration
+// ============================================================================
/**
- * Functor instance for ImmutableArrayK
- * Maps over immutable arrays while preserving immutability
+ * Immutable Functor instance for arrays
*/
-export const ImmutableArrayFunctor: Functor<ImmutableArrayK> = {
- map: <A, B>(fa: ImmutableArray<A>, f: (a: A) => B): ImmutableArray<B> =>
- fa.map(f)
+export const ImmutableArrayFunctor: Functor<ArrayK> = {
+ map: <A, B>(fa: Immutable<A[]>, f: (a: A) => B): Immutable<B[]> => {
+ return Object.freeze(fa.map(f)) as Immutable<B[]>;
+ }
};
/**
- * Applicative instance for ImmutableArrayK
- * Provides pure and ap operations for immutable arrays
+ * Immutable Applicative instance for arrays
*/
-export const ImmutableArrayApplicative: Applicative<ImmutableArrayK> = {
+export const ImmutableArrayApplicative: Applicative<ArrayK> = {
...ImmutableArrayFunctor,
- of: <A>(a: A): ImmutableArray<A> => [a],
- ap: <A, B>(fab: ImmutableArray<(a: A) => B>, fa: ImmutableArray<A>): ImmutableArray<B> => {
+ of: <A>(a: A): Immutable<A[]> => {
+ return Object.freeze([a]) as Immutable<A[]>;
+ },
+ ap: <A, B>(fab: Immutable<((a: A) => B)[]>, fa: Immutable<A[]>): Immutable<B[]> => {
const result: B[] = [];
for (const f of fab) {
for (const a of fa) {
result.push(f(a));
}
}
- return result;
+ return Object.freeze(result) as Immutable<B[]>;
}
};
/**
- * Monad instance for ImmutableArrayK
- * Provides chain operation for immutable arrays
+ * Immutable Monad instance for arrays
*/
-export const ImmutableArrayMonad: Monad<ImmutableArrayK> = {
+export const ImmutableArrayMonad: Monad<ArrayK> = {
...ImmutableArrayApplicative,
- chain: <A, B>(fa: ImmutableArray<A>, f: (a: A) => ImmutableArray<B>): ImmutableArray<B> =>
- fa.flatMap(f)
-};
-
-/**
- * Functor instance for ImmutableSetK
- * Maps over immutable sets while preserving immutability
- */
-export const ImmutableSetFunctor: Functor<ImmutableSetK> = {
- map: <A, B>(fa: ReadonlySet<A>, f: (a: A) => B): ReadonlySet<B> =>
- new Set(Array.from(fa).map(f))
-};
-
-/**
- * Functor instance for ImmutableMapK
- * Maps over immutable map values while preserving immutability
- */
-export const ImmutableMapFunctor: Functor<ImmutableMapK> = {
- map: <A, B>(fa: ReadonlyMap<any, A>, f: (a: A) => B): ReadonlyMap<any, B> => {
- const newMap = new Map();
- for (const [key, value] of fa) {
- newMap.set(key, f(value));
+ chain: <A, B>(fa: Immutable<A[]>, f: (a: A) => Immutable<B[]>): Immutable<B[]> => {
+ const result: B[] = [];
+ for (const a of fa) {
+ const fb = f(a);
+ for (const b of fb) {
+ result.push(b);
+ }
}
- return newMap;
+ return Object.freeze(result) as Immutable<B[]>;
}
};
/**
- * Bifunctor instance for ImmutableMapK
- * Maps over both keys and values of immutable maps
+ * Immutable Traversable instance for arrays
*/
-export const ImmutableMapBifunctor: Bifunctor<ImmutableMapK> = {
- bimap: <A, B, C, D>(
- fab: ReadonlyMap<A, B>,
- f: (a: A) => C,
- g: (b: B) => D
- ): ReadonlyMap<C, D> => {
- const newMap = new Map();
- for (const [key, value] of fab) {
- newMap.set(f(key), g(value));
- }
- return newMap;
+export const ImmutableArrayTraversable: Traversable<ArrayK> = {
+ ...ImmutableArrayFunctor,
+ sequence: <A>(fas: Immutable<A[][]>): Immutable<A[]> => {
+ // Simplified implementation - in practice would need proper applicative
+ return Object.freeze(fas.flat()) as Immutable<A[]>;
+ },
+ traverse: <F extends Kind1, A, B>(
+ F: Applicative<F>,
+ fa: Immutable<A[]>,
+ f: (a: A) => Apply<F, [B]>
+ ): Apply<F, [Immutable<B[]>]> => {
+ // Simplified implementation - in practice would need proper applicative
+ return F.of(Object.freeze(fa.map(a => (f(a) as any).value)) as Immutable<B[]>) as any;
}
};
/**
- * Immutable GADT wrapper
- * Makes GADT payloads immutable
+ * Immutable Foldable instance for arrays
*/
-export type ImmutableGADT<Tag extends string, Payload> = {
- readonly tag: Tag;
- readonly payload: DeepImmutable<Payload>;
+export const ImmutableArrayFoldable: Foldable<ArrayK> = {
+ reduce: <A, B>(fa: Immutable<A[]>, f: (b: B, a: A) => B, b: B): B => {
+ return fa.reduce(f, b);
+ },
+ foldMap: <M, A>(M: any, fa: Immutable<A[]>, f: (a: A) => M): M => {
+ return fa.reduce((acc, a) => M.concat(acc, f(a)), M.empty());
+ }
};
-/**
- * Immutable Expr GADT
- */
-export type ImmutableExpr<A> =
- | ImmutableGADT<'Const', { value: A }>
- | ImmutableGADT<'Add', { left: ImmutableExpr<number>; right: ImmutableExpr<number> }>
- | ImmutableGADT<'If', { cond: ImmutableExpr<boolean>; then: ImmutableExpr<A>; else: ImmutableExpr<A> }>
- | ImmutableGADT<'Var', { name: string }>
- | ImmutableGADT<'Let', { name: string; value: ImmutableExpr<A>; body: ImmutableExpr<A> }>;
+// ============================================================================
+// Part 7: Readonly Pattern Matching
+// ============================================================================