ordofp_core 0.1.0

OrdoFP core provides developers with HList, Disiunctio, NominataUniversalis, Universalis, and functional type classes
Documentation
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
//! Campus - Field access traits for row polymorphism
//!
//! > *"Campus est locus apertus."*
//! > — A field is an open place.
//!
//! This module provides traits for accessing, extending, and restricting
//! fields in row-polymorphic records.

use crate::hlist::{Coniunctio, HList, Nihil};
use crate::indices::{Here, There};
use crate::labelled::{Field, field_with_name};

// =============================================================================
// HasField - Field Presence Constraint
// =============================================================================

/// Trait indicating a row contains a field with a specific label and type.
///
/// This is the core trait for row polymorphism - it allows functions to
/// require that a record contains certain fields without specifying the
/// complete record type.
///
/// # Latin Etymology
///
/// *Habet* = has, possesses
/// *Campus* = field
///
/// # Example
///
/// ```rust
/// use ordofp_core::rows::HabetCampum;
/// use ordofp_core::labelled::chars::*;
/// use ordofp_core::indices::Here;
/// use ordofp_core::{hlist, field};
///
/// type Name = (Ln, La, Lm, Le);
///
/// fn get_name<R, I>(record: &R) -> &str
/// where
///     R: HabetCampum<Name, String, I>,
/// {
///     record.get_field()
/// }
///
/// let record = hlist![field!(Name, String::from("Alice"))];
/// assert_eq!(get_name::<_, Here>(&record), "Alice");
/// ```
pub trait HabetCampum<Label, Value, Index> {
    /// Get a reference to the field value.
    fn get_field(&self) -> &Value;

    /// Get a mutable reference to the field value.
    fn get_field_mut(&mut self) -> &mut Value;
}

/// Implementation when the field is at the head.
impl<Label, Value, Tail: HList> HabetCampum<Label, Value, Here>
    for Coniunctio<Field<Label, Value>, Tail>
{
    #[inline]
    fn get_field(&self) -> &Value {
        &self.head.value
    }

    #[inline]
    fn get_field_mut(&mut self) -> &mut Value {
        &mut self.head.value
    }
}

/// Implementation when the field is in the tail.
impl<Label, Value, Head, Tail, TailIndex> HabetCampum<Label, Value, There<TailIndex>>
    for Coniunctio<Head, Tail>
where
    Tail: HabetCampum<Label, Value, TailIndex>,
{
    #[inline]
    fn get_field(&self) -> &Value {
        self.tail.get_field()
    }

    #[inline]
    fn get_field_mut(&mut self) -> &mut Value {
        self.tail.get_field_mut()
    }
}

// =============================================================================
// Extendo - Record Extension
// =============================================================================

/// Trait for extending a record with a new field.
///
/// # Latin Etymology
///
/// *Extendo* = to extend, stretch out
///
/// # Example
///
/// ```rust
/// use ordofp_core::rows::Extendo;
/// use ordofp_core::labelled::chars::*;
/// use ordofp_core::hlist::Nihil;
///
/// type Name = (Ln, La, Lm, Le);
/// type Age = (La, Lg, Le);
///
/// let record = Extendo::<Age, i32>::extend(
///     Extendo::<Name, &str>::extend(Nihil, "name", "Alice"),
///     "age",
///     30,
/// );
/// assert_eq!(record.head.value, 30);
/// assert_eq!(record.tail.head.value, "Alice");
/// ```
pub trait Extendo<Label, Value>: Sized {
    /// The result type after extending.
    type Output;

    /// Extend the record with a new field.
    fn extend(self, name: &'static str, value: Value) -> Self::Output;
}

/// Extending Nihil creates a single-field record.
impl<Label, Value> Extendo<Label, Value> for Nihil {
    type Output = Coniunctio<Field<Label, Value>, Nihil>;

    #[inline]
    fn extend(self, name: &'static str, value: Value) -> Self::Output {
        Coniunctio {
            head: field_with_name(name, value),
            tail: Nihil,
        }
    }
}

/// Extending a non-empty record prepends the new field.
impl<Label, Value, Head, Tail: HList> Extendo<Label, Value> for Coniunctio<Head, Tail> {
    type Output = Coniunctio<Field<Label, Value>, Coniunctio<Head, Tail>>;

    #[inline]
    fn extend(self, name: &'static str, value: Value) -> Self::Output {
        Coniunctio {
            head: field_with_name(name, value),
            tail: self,
        }
    }
}

// =============================================================================
// Restricto - Field Removal
// =============================================================================

/// Trait for removing a field from a record.
///
/// Returns the field value and the record with the field removed.
///
/// # Latin Etymology
///
/// *Restricto* = to restrict, confine, remove
///
/// # Example
///
/// ```rust
/// use ordofp_core::rows::Restricto;
/// use ordofp_core::labelled::chars::*;
/// use ordofp_core::indices::Here;
/// use ordofp_core::{hlist, field};
///
/// type Age = (La, Lg, Le);
///
/// let record = hlist![field!(Age, 30i32)];
/// let (age, rest) = Restricto::<Age, Here>::restrict(record);
/// assert_eq!(age, 30);
/// assert!(rest.is_empty());
/// ```
pub trait Restricto<Label, Index>: Sized {
    /// The type of the removed value.
    type Value;

    /// The record type after removal.
    type Remainder;

    /// Remove a field by label and return it along with the remainder.
    fn restrict(self) -> (Self::Value, Self::Remainder);
}

/// Restricting when the field is at the head.
impl<Label, Value, Tail: HList> Restricto<Label, Here> for Coniunctio<Field<Label, Value>, Tail> {
    type Value = Value;
    type Remainder = Tail;

    #[inline]
    fn restrict(self) -> (Self::Value, Self::Remainder) {
        (self.head.value, self.tail)
    }
}

/// Restricting when the field is in the tail.
impl<Label, Head, Tail, TailIndex> Restricto<Label, There<TailIndex>> for Coniunctio<Head, Tail>
where
    Tail: Restricto<Label, TailIndex>,
{
    type Value = Tail::Value;
    type Remainder = Coniunctio<Head, Tail::Remainder>;

    #[inline]
    fn restrict(self) -> (Self::Value, Self::Remainder) {
        let (value, tail_remainder) = self.tail.restrict();
        (
            value,
            Coniunctio {
                head: self.head,
                tail: tail_remainder,
            },
        )
    }
}

// =============================================================================
// Merge - Record Merging
// =============================================================================

/// Trait for merging two records together.
///
/// The resulting record contains all fields from both records.
///
/// # Latin Etymology
///
/// *Confluo* = to flow together, merge
///
/// # Example
///
/// ```rust
/// use ordofp_core::rows::Confluo;
/// use ordofp_core::labelled::chars::*;
/// use ordofp_core::{hlist, field};
///
/// type Name = (Ln, La, Lm, Le);
/// type Age = (La, Lg, Le);
///
/// let name_record = hlist![field!(Name, "Alice")];
/// let age_record = hlist![field!(Age, 30i32)];
///
/// let person = name_record.merge(age_record);
/// assert_eq!(person.head.value, "Alice");
/// assert_eq!(person.tail.head.value, 30);
/// ```
pub trait Confluo<Other>: Sized {
    /// The merged record type.
    type Output;

    /// Merge this record with another.
    fn merge(self, other: Other) -> Self::Output;
}

/// Merging with empty record returns self.
impl<T: HList> Confluo<Nihil> for T {
    type Output = T;

    #[inline]
    fn merge(self, _: Nihil) -> Self::Output {
        self
    }
}

/// Merging empty record with any record returns the other.
impl<Head, Tail: HList> Confluo<Coniunctio<Head, Tail>> for Nihil {
    type Output = Coniunctio<Head, Tail>;

    #[inline]
    fn merge(self, other: Coniunctio<Head, Tail>) -> Self::Output {
        other
    }
}

/// Merging two non-empty records.
impl<H1, T1: HList + Confluo<Coniunctio<H2, T2>>, H2, T2: HList> Confluo<Coniunctio<H2, T2>>
    for Coniunctio<H1, T1>
{
    type Output = Coniunctio<H1, T1::Output>;

    #[inline]
    fn merge(self, other: Coniunctio<H2, T2>) -> Self::Output {
        Coniunctio {
            head: self.head,
            tail: self.tail.merge(other),
        }
    }
}

// =============================================================================
// Rename - Field Renaming
// =============================================================================

/// Trait for renaming a field in a record.
///
/// # Latin Etymology
///
/// *Renomino* = to rename
pub trait Renomino<OldLabel, NewLabel, Index>: Sized {
    /// The record type after renaming.
    type Output;

    /// Rename a field.
    fn rename(self, new_name: &'static str) -> Self::Output;
}

/// Renaming when the field is at the head.
impl<OldLabel, NewLabel, Value, Tail: HList> Renomino<OldLabel, NewLabel, Here>
    for Coniunctio<Field<OldLabel, Value>, Tail>
{
    type Output = Coniunctio<Field<NewLabel, Value>, Tail>;

    #[inline]
    fn rename(self, new_name: &'static str) -> Self::Output {
        Coniunctio {
            head: field_with_name(new_name, self.head.value),
            tail: self.tail,
        }
    }
}

/// Renaming when the field is in the tail.
impl<OldLabel, NewLabel, Head, Tail, TailIndex> Renomino<OldLabel, NewLabel, There<TailIndex>>
    for Coniunctio<Head, Tail>
where
    Tail: Renomino<OldLabel, NewLabel, TailIndex>,
{
    type Output = Coniunctio<Head, Tail::Output>;

    #[inline]
    fn rename(self, new_name: &'static str) -> Self::Output {
        Coniunctio {
            head: self.head,
            tail: self.tail.rename(new_name),
        }
    }
}

// =============================================================================
// Modify - Field Modification
// =============================================================================

/// Trait for modifying a field value in a record.
///
/// # Latin Etymology
///
/// *Muto* = to change, modify
pub trait Muto<Label, NewValue, Index>: Sized {
    /// The original value type.
    type OldValue;

    /// The record type after modification.
    type Output;

    /// Modify a field with a function.
    fn modify<F>(self, f: F) -> Self::Output
    where
        F: FnOnce(Self::OldValue) -> NewValue;
}

/// Modifying when the field is at the head.
impl<Label, OldValue, NewValue, Tail: HList> Muto<Label, NewValue, Here>
    for Coniunctio<Field<Label, OldValue>, Tail>
{
    type OldValue = OldValue;
    type Output = Coniunctio<Field<Label, NewValue>, Tail>;

    #[inline]
    fn modify<F>(self, f: F) -> Self::Output
    where
        F: FnOnce(Self::OldValue) -> NewValue,
    {
        Coniunctio {
            head: field_with_name(self.head.name, f(self.head.value)),
            tail: self.tail,
        }
    }
}

/// Modifying when the field is in the tail.
impl<Label, NewValue, Head, Tail, TailIndex> Muto<Label, NewValue, There<TailIndex>>
    for Coniunctio<Head, Tail>
where
    Tail: Muto<Label, NewValue, TailIndex>,
{
    type OldValue = Tail::OldValue;
    type Output = Coniunctio<Head, Tail::Output>;

    #[inline]
    fn modify<F>(self, f: F) -> Self::Output
    where
        F: FnOnce(Self::OldValue) -> NewValue,
    {
        Coniunctio {
            head: self.head,
            tail: self.tail.modify(f),
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::labelled::chars::*;

    type Name = (Ln, La, Lm, Le);
    type Age = (La, Lg, Le);

    #[test]
    fn test_habet_campum_head() {
        let record = hlist![field!(Name, "Alice")];
        let name: &&str = HabetCampum::<Name, &str, Here>::get_field(&record);
        assert_eq!(*name, "Alice");
    }

    #[test]
    fn test_habet_campum_tail() {
        let record = hlist![field!(Age, 30i32), field!(Name, "Alice")];
        let name: &&str = HabetCampum::<Name, &str, There<Here>>::get_field(&record);
        assert_eq!(*name, "Alice");
    }

    #[test]
    fn test_extendo_nihil() {
        let record: Coniunctio<Field<Name, &str>, Nihil> =
            Extendo::<Name, &str>::extend(Nihil, "name", "Alice");
        assert_eq!(record.head.value, "Alice");
    }

    #[test]
    fn test_extendo_non_empty() {
        let record = hlist![field!(Name, "Alice")];
        let extended = Extendo::<Age, i32>::extend(record, "age", 30i32);
        assert_eq!(extended.head.value, 30);
        assert_eq!(extended.tail.head.value, "Alice");
    }

    #[test]
    fn test_restricto_head() {
        let record = hlist![field!(Name, "Alice"), field!(Age, 30i32)];
        let (name, rest): (&str, _) = Restricto::<Name, Here>::restrict(record);
        assert_eq!(name, "Alice");
        assert_eq!(rest.head.value, 30);
    }

    #[test]
    fn test_restricto_tail() {
        let record = hlist![field!(Age, 30i32), field!(Name, "Alice")];
        let (name, rest): (&str, _) = Restricto::<Name, There<Here>>::restrict(record);
        assert_eq!(name, "Alice");
        assert_eq!(rest.head.value, 30);
    }

    #[test]
    fn test_confluo_empty() {
        let record = hlist![field!(Name, "Alice")];
        let merged = record.merge(Nihil);
        assert_eq!(merged.head.value, "Alice");
    }

    #[test]
    fn test_confluo_two_records() {
        let r1 = hlist![field!(Name, "Alice")];
        let r2 = hlist![field!(Age, 30i32)];
        let merged = r1.merge(r2);
        assert_eq!(merged.head.value, "Alice");
        assert_eq!(merged.tail.head.value, 30);
    }

    #[test]
    fn test_muto() {
        let record = hlist![field!(Age, 30i32)];
        let modified = Muto::<Age, i32, Here>::modify(record, |age| age + 1);
        assert_eq!(modified.head.value, 31);
    }

    #[test]
    fn test_renomino() {
        type NewName = (Ln, Le, Lw, DoubleUnderscore, Ln, La, Lm, Le);
        let record = hlist![field!(Name, "Alice")];
        let renamed: Coniunctio<Field<NewName, &str>, Nihil> =
            Renomino::<Name, NewName, Here>::rename(record, "new_name");
        assert_eq!(renamed.head.name, "new_name");
        assert_eq!(renamed.head.value, "Alice");
    }
}