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
//! # Iso-based Prism
//!
//! This module provides a Prism optic based on the Iso abstraction.
//! A Prism is an optic that allows safe and functional access to a variant of a sum type (such as an enum),
//! and the ability to construct the sum type from the focused value.
//!
//! ## Core Idea
//!
//! - A Prism can be represented as a pair of functions:
//! - `preview: S -> Option<A>`
//! - `review: A -> S`
//! - `IsoPrism` encodes this pair using an [`Iso`] with `To = Option<A>`:
//! - `Iso::forward` is used as `preview`
//! - `Iso::backward` is used as `review` by always passing `Some(a)`
//!
//! Note: In general, `S <-> Option<A>` is *not* a true isomorphism for sum types (many `S` values map to `None`).
//! `IsoPrism` can still be useful as a convenient encoding of `preview/review`, but the usual prism laws only hold
//! to the extent that the provided [`Iso`] behaves lawfully for the cases you care about.
//!
//! ## Functional Programming Context
//!
//! In functional programming, a Prism is a type of optic used for handling sum types (like enums in Rust).
//! Unlike Lens, which focuses on product types (like structs), Prisms handle cases where the focus might not
//! exist. This makes them particularly suitable for enum variants.
//!
//! The IsoPrism implementation specifically builds on the concept of isomorphisms (Iso), adapting
//! them to the partial nature of Prisms. This representation provides several advantages:
//!
//! - **Composable Abstractions**: IsoPrisms can be composed with other optics following function composition semantics
//! - **Type Safety**: Leverages Rust's type system to ensure correct handling of variants
//! - **Functional Purity**: Operations maintain referential transparency and avoid side effects
//! - **Law Abidance**: Follows the standard optic laws expected of well-behaved Prisms
//!
//! Related concepts in other functional languages include:
//!
//! - Haskell's Prism in libraries like lens
//! - Scala's Prism in libraries like Monocle
//! - PureScript's Prism
//! - TypeScript's Prism in fp-ts-optics
//!
//! ## Type Class Implementations
//!
//! IsoPrism implements several important functional programming interfaces:
//!
//! - **Composable Optic**: Prisms can be composed with other prisms using the `compose` method
//! - **Optional Getter**: Safely extracts a value if it exists via the `preview` method
//! - **Constructor**: Creates a value of the parent type from the focus type via `review`
//!
//! ## Examples
//!
//! ### Basic Usage
//!
//! ```rust
//! use rustica::datatypes::iso_prism::IsoPrism;
//! use rustica::traits::iso::Iso;
//!
//! #[derive(Clone, Debug, PartialEq)]
//! enum MyEnum {
//! Foo(i32),
//! Bar(String),
//! }
//!
//! struct FooPrismIso;
//! impl Iso<MyEnum, Option<i32>> for FooPrismIso {
//! type From = MyEnum;
//! type To = Option<i32>;
//! fn forward(&self, from: &MyEnum) -> Option<i32> {
//! match from {
//! MyEnum::Foo(x) => Some(*x),
//! _ => None,
//! }
//! }
//! fn backward(&self, to: &Option<i32>) -> MyEnum {
//! match to {
//! Some(x) => MyEnum::Foo(*x),
//! None => MyEnum::Bar("default".to_string()),
//! }
//! }
//! }
//!
//! let prism = IsoPrism::new(FooPrismIso);
//! let foo = MyEnum::Foo(10);
//! assert_eq!(prism.preview(&foo), Some(10));
//! let bar = MyEnum::Bar("hi".to_string());
//! assert_eq!(prism.preview(&bar), None);
//! let reviewed = prism.review(&20);
//! assert_eq!(reviewed, MyEnum::Foo(20));
//! ```
//!
//! ### Composing IsoPrisms
//!
//! ```rust
//! use rustica::datatypes::iso_prism::IsoPrism;
//! use rustica::traits::iso::Iso;
//! use std::marker::PhantomData;
//!
//! // Nested enum structure
//! #[derive(Clone, Debug, PartialEq)]
//! enum Shape {
//! Circle { radius: f64 },
//! Rectangle { width: f64, height: f64 },
//! }
//!
//! #[derive(Clone, Debug, PartialEq)]
//! enum Drawing {
//! Shape(Shape),
//! Text(String),
//! }
//!
//! // Iso for focusing on the Shape variant in Drawing
//! struct ShapeIso;
//! impl Iso<Drawing, Option<Shape>> for ShapeIso {
//! type From = Drawing;
//! type To = Option<Shape>;
//!
//! fn forward(&self, from: &Drawing) -> Option<Shape> {
//! match from {
//! Drawing::Shape(shape) => Some(shape.clone()),
//! _ => None,
//! }
//! }
//!
//! fn backward(&self, to: &Option<Shape>) -> Drawing {
//! match to {
//! Some(shape) => Drawing::Shape(shape.clone()),
//! None => Drawing::Text("Placeholder".to_string()),
//! }
//! }
//! }
//!
//! // Iso for focusing on the Circle variant in Shape
//! struct CircleIso;
//! impl Iso<Shape, Option<f64>> for CircleIso {
//! type From = Shape;
//! type To = Option<f64>;
//!
//! fn forward(&self, from: &Shape) -> Option<f64> {
//! match from {
//! Shape::Circle { radius } => Some(*radius),
//! _ => None,
//! }
//! }
//!
//! fn backward(&self, to: &Option<f64>) -> Shape {
//! match to {
//! Some(radius) => Shape::Circle { radius: *radius },
//! None => Shape::Rectangle { width: 0.0, height: 0.0 },
//! }
//! }
//! }
//!
//! // Create the prisms
//! let shape_prism = IsoPrism::new(ShapeIso);
//! let circle_prism = IsoPrism::new(CircleIso);
//!
//! // Compose them to get a prism that focuses on Circle within Drawing
//! let circle_in_drawing_prism = shape_prism.compose(circle_prism);
//!
//! // Use the composed prism
//! let circle_drawing = Drawing::Shape(Shape::Circle { radius: 5.0 });
//! let rect_drawing = Drawing::Shape(Shape::Rectangle { width: 3.0, height: 4.0 });
//! let text_drawing = Drawing::Text("Hello".to_string());
//!
//! // Extract the radius from various drawings
//! assert_eq!(circle_in_drawing_prism.preview(&circle_drawing), Some(5.0));
//! assert_eq!(circle_in_drawing_prism.preview(&rect_drawing), None);
//! assert_eq!(circle_in_drawing_prism.preview(&text_drawing), None);
//!
//! // Create a new drawing with a circle of radius 10.0
//! let new_circle_drawing = circle_in_drawing_prism.review(&10.0);
//! assert_eq!(new_circle_drawing, Drawing::Shape(Shape::Circle { radius: 10.0 }));
//! ```
//!
//! ## Type Class Laws
//!
//! The `IsoPrism` type follows the standard prism laws. See the documentation for
//! the specific functions (`preview`, `review`) for examples demonstrating these laws.
//!
//! ### Review-Preview Law
//!
//! For any prism `p` and focus value `a`:
//!
//! `p.preview(&p.review(&a)) == Some(a)`
//!
//! If you review a value and then preview the result, you get back the original value.
//!
//! ### Preview-Review Law
//!
//! For any prism `p`, structure `s`, and focus value `a` where `p.preview(s) = Some(a)`:
//!
//! `p.review(&a) == s`
//!
//! If you can preview a value from a structure, then reviewing that value should give you back
//! the original structure.
//!
//! See also: [`crate::datatypes::prism`], [`crate::traits::iso::Iso`]
use crate;
use PhantomData;
/// Iso-based Prism optic.
///
/// This struct represents a Prism built on top of an Iso abstraction.
/// It allows safe and functional partial access to a variant of a sum type (e.g., enum variant),
/// and the ability to construct the sum type from the focused value.
///
/// # Design Notes
///
/// * IsoPrism implements a prism using Iso's bidirectional mapping capabilities
/// * The abstraction treats the Prism as an isomorphism between S and `Option<A>`
/// * A well-behaved IsoPrism should uphold the prism laws
/// * Composition of IsoPrisms follows function composition semantics
///
/// # Type Parameters
/// * `S` - The sum type (e.g., enum)
/// * `A` - The type of the focused variant
/// * `L` - The Iso implementation from `S` to `Option<A>`
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use rustica::datatypes::iso_prism::IsoPrism;
/// use rustica::traits::iso::Iso;
///
/// // Define an enum (sum type)
/// #[derive(Clone, Debug, PartialEq)]
/// enum Result<T, E> {
/// Ok(T),
/// Err(E),
/// }
///
/// // Create an Iso for the Ok variant
/// struct OkIso<T, E>(std::marker::PhantomData<(T, E)>);
///
/// impl<T: Clone, E> Iso<Result<T, E>, Option<T>> for OkIso<T, E> {
/// type From = Result<T, E>;
/// type To = Option<T>;
///
/// fn forward(&self, from: &Result<T, E>) -> Option<T> {
/// match from {
/// Result::Ok(t) => Some(t.clone()),
/// Result::Err(_) => None,
/// }
/// }
///
/// fn backward(&self, to: &Option<T>) -> Result<T, E> {
/// match to {
/// Some(t) => Result::Ok(t.clone()),
/// None => panic!("Cannot construct Err variant without an error value"),
/// }
/// }
/// }
///
/// // Create and use the prism
/// let ok_prism = IsoPrism::new(OkIso(std::marker::PhantomData));
/// let ok_value = Result::Ok::<_, &str>("success".to_string());
/// let err_value = Result::Err::<String, _>("error");
///
/// assert_eq!(ok_prism.preview(&ok_value), Some("success".to_string()));
/// assert_eq!(ok_prism.preview(&err_value), None);
/// assert_eq!(ok_prism.review(&"new success".to_string()), Result::Ok("new success".to_string()));
/// ```
type ComposedIsoPrism<S, B, L, L2, A> =
;
/// Lifts a prism to work with `Option`s.
///
/// This struct is used to lift a prism to work with `Option`s, allowing it to be composed with other prisms.