frunk_core/
hlist.rs

1//! Module that holds HList data structures, implementations, and typeclasses.
2//!
3//! Typically, you would want to use the `hlist!` macro to make it easier
4//! for you to use HList.
5//!
6//! # Examples
7//!
8//! ```
9//! # fn main() {
10//! use frunk_core::{hlist, HList, poly_fn};
11//!
12//! let h = hlist![1, "hi"];
13//! assert_eq!(h.len(), 2);
14//! let (a, b) = h.into_tuple2();
15//! assert_eq!(a, 1);
16//! assert_eq!(b, "hi");
17//!
18//! // Reverse
19//! let h1 = hlist![true, "hi"];
20//! assert_eq!(h1.into_reverse(), hlist!["hi", true]);
21//!
22//! // foldr (foldl also available)
23//! let h2 = hlist![1, false, 42f32];
24//! let folded = h2.foldr(
25//!             hlist![|acc, i| i + acc,
26//!                    |acc, _| if acc > 42f32 { 9000 } else { 0 },
27//!                    |acc, f| f + acc],
28//!             1f32
29//!     );
30//! assert_eq!(folded, 9001);
31//!
32//! let h3 = hlist![9000, "joe", 41f32];
33//! // Mapping over an HList with a polymorphic function,
34//! // declared using the poly_fn! macro (you can choose to impl
35//! // it manually)
36//! let mapped = h3.map(
37//!   poly_fn![
38//!     |f: f32|   -> f32 { f + 1f32 },
39//!     |i: isize| -> isize { i + 1 },
40//!     ['a] |s: &'a str| -> &'a str { s }
41//!   ]);
42//! assert_eq!(mapped, hlist![9001, "joe", 42f32]);
43//!
44//! // Plucking a value out by type
45//! let h4 = hlist![1, "hello", true, 42f32];
46//! let (t, remainder): (bool, _) = h4.pluck();
47//! assert!(t);
48//! assert_eq!(remainder, hlist![1, "hello", 42f32]);
49//!
50//! // Resculpting an HList
51//! let h5 = hlist![9000, "joe", 41f32, true];
52//! let (reshaped, remainder2): (HList![f32, i32, &str], _) = h5.sculpt();
53//! assert_eq!(reshaped, hlist![41f32, 9000, "joe"]);
54//! assert_eq!(remainder2, hlist![true]);
55//! # }
56//! ```
57
58use crate::indices::{Here, Suffixed, There};
59use crate::traits::{Func, IntoReverse, Poly, ToMut, ToRef};
60#[cfg(feature = "alloc")]
61use alloc::vec::Vec;
62#[cfg(feature = "serde")]
63use serde::{Deserialize, Serialize};
64
65use core::ops::Add;
66
67/// Typeclass for HList-y behaviour
68///
69/// An HList is a heterogeneous list, one that is statically typed at compile time. In simple terms,
70/// it is just an arbitrarily-nested Tuple2.
71pub trait HList: Sized {
72    /// Returns the length of a given HList type without making use of any references, or
73    /// in fact, any values at all.
74    ///
75    /// # Examples
76    /// ```
77    /// # fn main() {
78    /// use frunk::prelude::*;
79    /// use frunk_core::HList;
80    ///
81    /// assert_eq!(<HList![i32, bool, f32]>::LEN, 3);
82    /// # }
83    /// ```
84    const LEN: usize;
85
86    /// Returns the length of a given HList
87    ///
88    /// # Examples
89    ///
90    /// ```
91    /// # fn main() {
92    /// use frunk_core::hlist;
93    ///
94    /// let h = hlist![1, "hi"];
95    /// assert_eq!(h.len(), 2);
96    /// # }
97    /// ```
98    #[inline]
99    fn len(&self) -> usize {
100        Self::LEN
101    }
102
103    /// Returns whether a given HList is empty
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// # fn main() {
109    /// use frunk_core::hlist;
110    ///
111    /// let h = hlist![];
112    /// assert!(h.is_empty());
113    /// # }
114    /// ```
115    #[inline]
116    fn is_empty(&self) -> bool {
117        Self::LEN == 0
118    }
119
120    /// Returns the length of a given HList type without making use of any references, or
121    /// in fact, any values at all.
122    ///
123    /// # Examples
124    /// ```
125    /// # fn main() {
126    /// use frunk::prelude::*;
127    /// use frunk_core::HList;
128    ///
129    /// assert_eq!(<HList![i32, bool, f32]>::static_len(), 3);
130    /// # }
131    /// ```
132    #[deprecated(since = "0.1.31", note = "Please use LEN instead")]
133    fn static_len() -> usize;
134
135    /// Prepends an item to the current HList
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// # fn main() {
141    /// use frunk_core::hlist;
142    ///
143    /// let h1 = hlist![1, "hi"];
144    /// let h2 = h1.prepend(true);
145    /// let (a, (b, c)) = h2.into_tuple2();
146    /// assert_eq!(a, true);
147    /// assert_eq!(b, 1);
148    /// assert_eq!(c, "hi");
149    /// # }
150    fn prepend<H>(self, h: H) -> HCons<H, Self> {
151        HCons {
152            head: h,
153            tail: self,
154        }
155    }
156}
157
158/// Represents the right-most end of a heterogeneous list
159///
160/// # Examples
161///
162/// ```
163/// # use frunk_core::hlist::{h_cons, HNil};
164/// let h = h_cons(1, HNil);
165/// let h = h.head;
166/// assert_eq!(h, 1);
167/// ```
168#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
169#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
170pub struct HNil;
171
172impl HList for HNil {
173    const LEN: usize = 0;
174    fn static_len() -> usize {
175        Self::LEN
176    }
177}
178
179/// Represents the most basic non-empty HList. Its value is held in `head`
180/// while its tail is another HList.
181#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
182#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
183pub struct HCons<H, T> {
184    pub head: H,
185    pub tail: T,
186}
187
188impl<H, T: HList> HList for HCons<H, T> {
189    const LEN: usize = 1 + <T as HList>::LEN;
190    fn static_len() -> usize {
191        Self::LEN
192    }
193}
194
195impl<H, T> HCons<H, T> {
196    /// Returns the head of the list and the tail of the list as a tuple2.
197    /// The original list is consumed
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// # fn main() {
203    /// use frunk_core::hlist;
204    ///
205    /// let h = hlist!("hi");
206    /// let (h, tail) = h.pop();
207    /// assert_eq!(h, "hi");
208    /// assert_eq!(tail, hlist![]);
209    /// # }
210    /// ```
211    pub fn pop(self) -> (H, T) {
212        (self.head, self.tail)
213    }
214}
215
216/// Takes an element and an Hlist and returns another one with
217/// the element prepended to the original list. The original list
218/// is consumed
219///
220/// # Examples
221///
222/// ```
223/// # extern crate frunk; fn main() {
224/// use frunk::hlist::{HNil, h_cons};
225///
226/// let h_list = h_cons("what", h_cons(1.23f32, HNil));
227/// let (h1, h2) = h_list.into_tuple2();
228/// assert_eq!(h1, "what");
229/// assert_eq!(h2, 1.23f32);
230/// # }
231/// ```
232pub fn h_cons<H, T: HList>(h: H, tail: T) -> HCons<H, T> {
233    HCons { head: h, tail }
234}
235
236// Inherent methods shared by HNil and HCons.
237macro_rules! gen_inherent_methods {
238    (impl<$($TyPar:ident),*> $Struct:ty { ... })
239    => {
240        impl<$($TyPar),*> $Struct {
241            /// Returns the length of a given HList
242            ///
243            /// # Examples
244            ///
245            /// ```
246            /// # fn main() {
247            /// use frunk_core::hlist;
248            ///
249            /// let h = hlist![1, "hi"];
250            /// assert_eq!(h.len(), 2);
251            /// # }
252            /// ```
253            #[inline(always)]
254            pub fn len(&self) -> usize
255            where Self: HList,
256            {
257                HList::len(self)
258            }
259
260            /// Returns whether a given HList is empty
261            ///
262            /// # Examples
263            ///
264            /// ```
265            /// # fn main() {
266            /// use frunk_core::hlist;
267            ///
268            /// let h = hlist![];
269            /// assert!(h.is_empty());
270            /// # }
271            /// ```
272            #[inline(always)]
273            pub fn is_empty(&self) -> bool
274            where Self: HList,
275            {
276                HList::is_empty(self)
277            }
278
279            /// Prepend an item to the current HList
280            ///
281            /// # Examples
282            ///
283            /// ```
284            /// # fn main() {
285            /// use frunk_core::hlist;
286            ///
287            /// let h1 = hlist![1, "hi"];
288            /// let h2 = h1.prepend(true);
289            /// let (a, (b, c)) = h2.into_tuple2();
290            /// assert_eq!(a, true);
291            /// assert_eq!(b, 1);
292            /// assert_eq!(c, "hi");
293            /// # }
294            #[inline(always)]
295            pub fn prepend<H>(self, h: H) -> HCons<H, Self>
296            where Self: HList,
297            {
298                HList::prepend(self, h)
299            }
300
301            /// Consume the current HList and return an HList with the requested shape.
302            ///
303            /// `sculpt` allows us to extract/reshape/sculpt the current HList into another shape,
304            /// provided that the requested shape's types are are contained within the current HList.
305            ///
306            /// The `Indices` type parameter allows the compiler to figure out that `Ts`
307            /// and `Self` can be morphed into each other.
308            ///
309            /// # Examples
310            ///
311            /// ```
312            /// # fn main() {
313            /// use frunk_core::{hlist, HList};
314            ///
315            /// let h = hlist![9000, "joe", 41f32, true];
316            /// let (reshaped, remainder): (HList![f32, i32, &str], _) = h.sculpt();
317            /// assert_eq!(reshaped, hlist![41f32, 9000, "joe"]);
318            /// assert_eq!(remainder, hlist![true]);
319            /// # }
320            /// ```
321            #[inline(always)]
322            pub fn sculpt<Ts, Indices>(self) -> (Ts, <Self as Sculptor<Ts, Indices>>::Remainder)
323            where Self: Sculptor<Ts, Indices>,
324            {
325                Sculptor::sculpt(self)
326            }
327
328            /// Reverse the HList.
329            ///
330            /// # Examples
331            ///
332            /// ```
333            /// # fn main() {
334            /// use frunk_core::hlist;
335            ///
336            /// assert_eq!(hlist![].into_reverse(), hlist![]);
337            ///
338            /// assert_eq!(
339            ///     hlist![1, "hello", true, 42f32].into_reverse(),
340            ///     hlist![42f32, true, "hello", 1],
341            /// )
342            /// # }
343            /// ```
344            #[inline(always)]
345            pub fn into_reverse(self) -> <Self as IntoReverse>::Output
346            where Self: IntoReverse,
347            {
348                IntoReverse::into_reverse(self)
349            }
350
351            /// Return an HList where the contents are references to
352            /// the original HList on which this method was called.
353            ///
354            /// # Examples
355            ///
356            /// ```
357            /// # fn main() {
358            /// use frunk_core::hlist;
359            ///
360            /// assert_eq!(hlist![].to_ref(), hlist![]);
361            ///
362            /// assert_eq!(hlist![1, true].to_ref(), hlist![&1, &true]);
363            /// # }
364            /// ```
365            #[inline(always)]
366            #[allow(clippy::wrong_self_convention)]
367            pub fn to_ref<'a>(&'a self) -> <Self as ToRef<'a>>::Output
368                where Self: ToRef<'a>,
369            {
370                ToRef::to_ref(self)
371            }
372
373            /// Return an `HList` where the contents are mutable references
374            /// to the original `HList` on which this method was called.
375            ///
376            /// # Examples
377            ///
378            /// ```
379            /// # fn main() {
380            /// use frunk_core::hlist;
381            ///
382            /// assert_eq!(hlist![].to_mut(), hlist![]);
383            ///
384            /// assert_eq!(hlist![1, true].to_mut(), hlist![&mut 1, &mut true]);
385            /// # }
386            /// ```
387            #[inline(always)]
388            pub fn to_mut<'a>(&'a mut self) -> <Self as ToMut<'a>>::Output
389            where
390                Self: ToMut<'a>,
391            {
392                ToMut::to_mut(self)
393            }
394
395            /// Apply a function to each element of an HList.
396            ///
397            /// This transforms some `HList![A, B, C, ..., E]` into some
398            /// `HList![T, U, V, ..., Z]`.  A variety of types are supported
399            /// for the folder argument:
400            ///
401            /// * An `hlist![]` of closures (one for each element).
402            /// * A single closure (for mapping an HList that is homogenous).
403            /// * A single [`Poly`].
404            ///
405            /// [`Poly`]: ../traits/struct.Poly.html
406            ///
407            /// # Examples
408            ///
409            /// ```
410            /// # fn main() {
411            /// use frunk::HNil;
412            /// use frunk_core::hlist;
413            ///
414            /// assert_eq!(HNil.map(HNil), HNil);
415            ///
416            /// let h = hlist![1, false, 42f32];
417            ///
418            /// // Sadly we need to help the compiler understand the bool type in our mapper
419            ///
420            /// let mapped = h.to_ref().map(hlist![
421            ///     |&n| n + 1,
422            ///     |b: &bool| !b,
423            ///     |&f| f + 1f32]);
424            /// assert_eq!(mapped, hlist![2, true, 43f32]);
425            ///
426            /// // There is also a value-consuming version that passes values to your functions
427            /// // instead of just references:
428            ///
429            /// let mapped2 = h.map(hlist![
430            ///     |n| n + 3,
431            ///     |b: bool| !b,
432            ///     |f| f + 8959f32]);
433            /// assert_eq!(mapped2, hlist![4, true, 9001f32]);
434            /// # }
435            /// ```
436            #[inline(always)]
437            pub fn map<F>(self, mapper: F) -> <Self as HMappable<F>>::Output
438            where Self: HMappable<F>,
439            {
440                HMappable::map(self, mapper)
441            }
442
443            /// Zip two HLists together.
444            ///
445            /// This zips a `HList![A1, B1, ..., C1]` with a `HList![A2, B2, ..., C2]`
446            /// to make a `HList![(A1, A2), (B1, B2), ..., (C1, C2)]`
447            ///
448            /// # Example
449            ///
450            /// ```
451            /// # fn main() {
452            /// use frunk::HNil;
453            /// use frunk_core::hlist;
454            ///
455            /// assert_eq!(HNil.zip(HNil), HNil);
456            ///
457            /// let h1 = hlist![1, false, 42f32];
458            /// let h2 = hlist![true, "foo", 2];
459            ///
460            /// let zipped = h1.zip(h2);
461            /// assert_eq!(zipped, hlist![
462            ///     (1, true),
463            ///     (false, "foo"),
464            ///     (42f32, 2),
465            /// ]);
466            /// # }
467            /// ```
468            #[inline(always)]
469            pub fn zip<Other>(self, other: Other) -> <Self as HZippable<Other>>::Zipped
470            where Self: HZippable<Other>,
471            {
472                HZippable::zip(self, other)
473            }
474
475            /// Perform a left fold over an HList.
476            ///
477            /// This transforms some `HList![A, B, C, ..., E]` into a single
478            /// value by visiting all of the elements in left-to-right order.
479            /// A variety of types are supported for the mapper argument:
480            ///
481            /// * An `hlist![]` of closures (one for each element).
482            /// * A single closure (for folding an HList that is homogenous).
483            /// * A single [`Poly`].
484            ///
485            /// The accumulator can freely change type over the course of the call.
486            /// When called with a list of `N` functions, an expanded form of the
487            /// implementation with type annotations might look something like this:
488            ///
489            /// ```ignore
490            /// let acc: Acc0 = init_value;
491            /// let acc: Acc1 = f1(acc, x1);
492            /// let acc: Acc2 = f2(acc, x2);
493            /// let acc: Acc3 = f3(acc, x3);
494            /// ...
495            /// let acc: AccN = fN(acc, xN);
496            /// acc
497            /// ```
498            ///
499            /// [`Poly`]: ../traits/struct.Poly.html
500            ///
501            /// # Examples
502            ///
503            /// ```
504            /// # fn main() {
505            /// use frunk_core::hlist;
506            ///
507            /// let nil = hlist![];
508            ///
509            /// assert_eq!(nil.foldl(hlist![], 0), 0);
510            ///
511            /// let h = hlist![1, false, 42f32];
512            ///
513            /// let folded = h.to_ref().foldl(
514            ///     hlist![
515            ///         |acc, &i| i + acc,
516            ///         |acc, b: &bool| if !b && acc > 42 { 9000f32 } else { 0f32 },
517            ///         |acc, &f| f + acc
518            ///     ],
519            ///     1
520            /// );
521            ///
522            /// assert_eq!(42f32, folded);
523            ///
524            /// // There is also a value-consuming version that passes values to your folding
525            /// // functions instead of just references:
526            ///
527            /// let folded2 = h.foldl(
528            ///     hlist![
529            ///         |acc, i| i + acc,
530            ///         |acc, b: bool| if !b && acc > 42 { 9000f32 } else { 0f32 },
531            ///         |acc, f| f + acc
532            ///     ],
533            ///     8918
534            /// );
535            ///
536            /// assert_eq!(9042f32, folded2)
537            /// # }
538            /// ```
539            #[inline(always)]
540            pub fn foldl<Folder, Acc>(
541                self,
542                folder: Folder,
543                acc: Acc,
544            ) -> <Self as HFoldLeftable<Folder, Acc>>::Output
545            where Self: HFoldLeftable<Folder, Acc>,
546            {
547                HFoldLeftable::foldl(self, folder, acc)
548            }
549
550            /// Perform a right fold over an HList.
551            ///
552            /// This transforms some `HList![A, B, C, ..., E]` into a single
553            /// value by visiting all of the elements in reverse order.
554            /// A variety of types are supported for the mapper argument:
555            ///
556            /// * An `hlist![]` of closures (one for each element).
557            /// * A single closure (for folding an HList that is homogenous),
558            ///   taken by reference.
559            /// * A single [`Poly`].
560            ///
561            /// The accumulator can freely change type over the course of the call.
562            ///
563            /// [`Poly`]: ../traits/struct.Poly.html
564            ///
565            /// # Comparison to `foldl`
566            ///
567            /// While the order of element traversal in `foldl` may seem more natural,
568            /// `foldr` does have its use cases, in particular when it is used to build
569            /// something that reflects the structure of the original HList (such as
570            /// folding an HList of `Option`s into an `Option` of an HList).
571            /// An implementation of such a function using `foldl` will tend to
572            /// reverse the list, while `foldr` will tend to preserve its order.
573            ///
574            /// The reason for this is because `foldr` performs what is known as
575            /// "structural induction;" it can be understood as follows:
576            ///
577            /// * Write out the HList in terms of [`h_cons`] and [`HNil`].
578            /// * Substitute each [`h_cons`] with a function,
579            ///   and substitute [`HNil`] with `init`
580            ///
581            /// ```text
582            /// the list:
583            ///     h_cons(x1, h_cons(x2, h_cons(x3, ...h_cons(xN, HNil)...)))
584            ///
585            /// becomes:
586            ///        f1( x1,    f2( x2,    f3( x3, ...   fN( xN, init)...)))
587            /// ```
588            ///
589            /// [`HNil`]: struct.HNil.html
590            /// [`h_cons`]: fn.h_cons.html
591            ///
592            /// # Examples
593            ///
594            /// ```
595            /// # fn main() {
596            /// use frunk_core::hlist;
597            ///
598            /// let nil = hlist![];
599            ///
600            /// assert_eq!(nil.foldr(hlist![], 0), 0);
601            ///
602            /// let h = hlist![1, false, 42f32];
603            ///
604            /// let folded = h.foldr(
605            ///     hlist![
606            ///         |acc, i| i + acc,
607            ///         |acc, b: bool| if !b && acc > 42f32 { 9000 } else { 0 },
608            ///         |acc, f| f + acc
609            ///     ],
610            ///     1f32
611            /// );
612            ///
613            /// assert_eq!(9001, folded)
614            /// # }
615            /// ```
616            #[inline(always)]
617            pub fn foldr<Folder, Init>(
618                self,
619                folder: Folder,
620                init: Init,
621            ) -> <Self as HFoldRightable<Folder, Init>>::Output
622            where Self: HFoldRightable<Folder, Init>,
623            {
624                HFoldRightable::foldr(self, folder, init)
625            }
626
627            /// Extend the contents of this HList with another HList
628            ///
629            /// This exactly the same as the [`Add`][Add] impl.
630            ///
631            /// [Add]: struct.HCons.html#impl-Add%3CRHS%3E-for-HCons%3CH,+T%3E
632            ///
633            /// # Examples
634            ///
635            /// ```
636            /// use frunk_core::hlist;
637            ///
638            /// let first = hlist![0u8, 1u16];
639            /// let second = hlist![2u32, 3u64];
640            ///
641            /// assert_eq!(first.extend(second), hlist![0u8, 1u16, 2u32, 3u64]);
642            /// ```
643            pub fn extend<Other>(
644                self,
645                other: Other
646            ) -> <Self as Add<Other>>::Output
647            where
648                Self: Add<Other>,
649                Other: HList,
650            {
651                self + other
652            }
653        }
654    };
655}
656
657gen_inherent_methods! {
658    impl<> HNil { ... }
659}
660gen_inherent_methods! {
661    impl<Head, Tail> HCons<Head, Tail> { ... }
662}
663
664// HCons-only inherent methods.
665impl<Head, Tail> HCons<Head, Tail> {
666    /// Borrow an element by type from an HList.
667    ///
668    /// # Examples
669    ///
670    /// ```
671    /// # fn main() {
672    /// use frunk_core::hlist;
673    ///
674    /// let h = hlist![1i32, 2u32, "hello", true, 42f32];
675    ///
676    /// // Often, type inference can figure out the type you want.
677    /// // You can help guide type inference when necessary by
678    /// // using type annotations.
679    /// let b: &bool = h.get();
680    /// if !b { panic!("no way!") };
681    ///
682    /// // If space is tight, you can also use turbofish syntax.
683    /// // The Index is still left to type inference by using `_`.
684    /// match *h.get::<u32, _>() {
685    ///     2 => { }
686    ///     _ => panic!("it can't be!!"),
687    /// }
688    /// # }
689    /// ```
690    #[inline(always)]
691    pub fn get<T, Index>(&self) -> &T
692    where
693        Self: Selector<T, Index>,
694    {
695        Selector::get(self)
696    }
697
698    /// Mutably borrow an element by type from an HList.
699    ///
700    /// # Examples
701    ///
702    /// ```
703    /// # fn main() {
704    /// use frunk_core::hlist;
705    ///
706    /// let mut h = hlist![1i32, true];
707    ///
708    /// // Type inference ensures we fetch the correct type.
709    /// *h.get_mut() = false;
710    /// *h.get_mut() = 2;
711    /// // *h.get_mut() = "neigh";  // Won't compile.
712    ///
713    /// assert_eq!(h, hlist![2i32, false]);
714    /// # }
715    /// ```
716    #[inline(always)]
717    pub fn get_mut<T, Index>(&mut self) -> &mut T
718    where
719        Self: Selector<T, Index>,
720    {
721        Selector::get_mut(self)
722    }
723
724    /// Remove an element by type from an HList.
725    ///
726    /// The remaining elements are returned along with it.
727    ///
728    /// # Examples
729    ///
730    /// ```
731    /// # fn main() {
732    /// use frunk_core::hlist;
733    ///
734    /// let list = hlist![1, "hello", true, 42f32];
735    ///
736    /// // Often, type inference can figure out the target type.
737    /// let (b, list): (bool, _) = list.pluck();
738    /// assert!(b);
739    ///
740    /// // When type inference will not suffice, you can use a turbofish.
741    /// // The Index is still left to type inference by using `_`.
742    /// let (s, list) = list.pluck::<i32, _>();
743    ///
744    /// // Each time we plucked, we got back a remainder.
745    /// // Let's check what's left:
746    /// assert_eq!(list, hlist!["hello", 42.0])
747    /// # }
748    /// ```
749    #[inline(always)]
750    pub fn pluck<T, Index>(self) -> (T, <Self as Plucker<T, Index>>::Remainder)
751    where
752        Self: Plucker<T, Index>,
753    {
754        Plucker::pluck(self)
755    }
756
757    /// Turns an HList into nested Tuple2s, which are less troublesome to pattern match
758    /// and have a nicer type signature.
759    ///
760    /// # Examples
761    ///
762    /// ```
763    /// # fn main() {
764    /// use frunk_core::hlist;
765    ///
766    /// let h = hlist![1, "hello", true, 42f32];
767    ///
768    /// // We now have a much nicer pattern matching experience
769    /// let (first,(second,(third, fourth))) = h.into_tuple2();
770    ///
771    /// assert_eq!(first ,       1);
772    /// assert_eq!(second, "hello");
773    /// assert_eq!(third ,    true);
774    /// assert_eq!(fourth,   42f32);
775    /// # }
776    /// ```
777    #[inline(always)]
778    pub fn into_tuple2(
779        self,
780    ) -> (
781        <Self as IntoTuple2>::HeadType,
782        <Self as IntoTuple2>::TailOutput,
783    )
784    where
785        Self: IntoTuple2,
786    {
787        IntoTuple2::into_tuple2(self)
788    }
789}
790
791impl<RHS> Add<RHS> for HNil
792where
793    RHS: HList,
794{
795    type Output = RHS;
796
797    fn add(self, rhs: RHS) -> RHS {
798        rhs
799    }
800}
801
802impl<H, T, RHS> Add<RHS> for HCons<H, T>
803where
804    T: Add<RHS>,
805    RHS: HList,
806{
807    type Output = HCons<H, <T as Add<RHS>>::Output>;
808
809    fn add(self, rhs: RHS) -> Self::Output {
810        HCons {
811            head: self.head,
812            tail: self.tail + rhs,
813        }
814    }
815}
816
817/// Trait for borrowing an HList element by type
818///
819/// This trait is part of the implementation of the inherent method
820/// [`HCons::get`]. Please see that method for more information.
821///
822/// You only need to import this trait when working with generic
823/// HLists of unknown type. If you have an HList of known type,
824/// then `list.get()` should "just work" even without the trait.
825///
826/// [`HCons::get`]: struct.HCons.html#method.get
827pub trait Selector<S, I> {
828    /// Borrow an element by type from an HList.
829    ///
830    /// Please see the [inherent method] for more information.
831    ///
832    /// The only difference between that inherent method and this
833    /// trait method is the location of the type parameters
834    /// (here, they are on the trait rather than the method).
835    ///
836    /// [inherent method]: struct.HCons.html#method.get
837    fn get(&self) -> &S;
838
839    /// Mutably borrow an element by type from an HList.
840    ///
841    /// Please see the [inherent method] for more information.
842    ///
843    /// The only difference between that inherent method and this
844    /// trait method is the location of the type parameters
845    /// (here, they are on the trait rather than the method).
846    ///
847    /// [inherent method]: struct.HCons.html#method.get_mut
848    fn get_mut(&mut self) -> &mut S;
849}
850
851impl<T, Tail> Selector<T, Here> for HCons<T, Tail> {
852    fn get(&self) -> &T {
853        &self.head
854    }
855
856    fn get_mut(&mut self) -> &mut T {
857        &mut self.head
858    }
859}
860
861impl<Head, Tail, FromTail, TailIndex> Selector<FromTail, There<TailIndex>> for HCons<Head, Tail>
862where
863    Tail: Selector<FromTail, TailIndex>,
864{
865    fn get(&self) -> &FromTail {
866        self.tail.get()
867    }
868
869    fn get_mut(&mut self) -> &mut FromTail {
870        self.tail.get_mut()
871    }
872}
873
874/// Trait defining extraction from a given HList
875///
876/// This trait is part of the implementation of the inherent method
877/// [`HCons::pluck`]. Please see that method for more information.
878///
879/// You only need to import this trait when working with generic
880/// HLists of unknown type. If you have an HList of known type,
881/// then `list.pluck()` should "just work" even without the trait.
882///
883/// [`HCons::pluck`]: struct.HCons.html#method.pluck
884pub trait Plucker<Target, Index> {
885    /// What is left after you pluck the target from the Self
886    type Remainder;
887
888    /// Remove an element by type from an HList.
889    ///
890    /// Please see the [inherent method] for more information.
891    ///
892    /// The only difference between that inherent method and this
893    /// trait method is the location of the type parameters.
894    /// (here, they are on the trait rather than the method)
895    ///
896    /// [inherent method]: struct.HCons.html#method.pluck
897    fn pluck(self) -> (Target, Self::Remainder);
898}
899
900/// Implementation when the pluck target is in head
901impl<T, Tail> Plucker<T, Here> for HCons<T, Tail> {
902    type Remainder = Tail;
903
904    fn pluck(self) -> (T, Self::Remainder) {
905        (self.head, self.tail)
906    }
907}
908
909/// Implementation when the pluck target is in the tail
910impl<Head, Tail, FromTail, TailIndex> Plucker<FromTail, There<TailIndex>> for HCons<Head, Tail>
911where
912    Tail: Plucker<FromTail, TailIndex>,
913{
914    type Remainder = HCons<Head, <Tail as Plucker<FromTail, TailIndex>>::Remainder>;
915
916    fn pluck(self) -> (FromTail, Self::Remainder) {
917        let (target, tail_remainder): (
918            FromTail,
919            <Tail as Plucker<FromTail, TailIndex>>::Remainder,
920        ) = <Tail as Plucker<FromTail, TailIndex>>::pluck(self.tail);
921        (
922            target,
923            HCons {
924                head: self.head,
925                tail: tail_remainder,
926            },
927        )
928    }
929}
930
931/// Trait for pulling out some subset of an HList, using type inference.
932///
933/// This trait is part of the implementation of the inherent method
934/// [`HCons::sculpt`]. Please see that method for more information.
935///
936/// You only need to import this trait when working with generic
937/// HLists of unknown type. If you have an HList of known type,
938/// then `list.sculpt()` should "just work" even without the trait.
939///
940/// [`HCons::sculpt`]: struct.HCons.html#method.sculpt
941pub trait Sculptor<Target, Indices> {
942    type Remainder;
943
944    /// Consumes the current HList and returns an HList with the requested shape.
945    ///
946    /// Please see the [inherent method] for more information.
947    ///
948    /// The only difference between that inherent method and this
949    /// trait method is the location of the type parameters.
950    /// (here, they are on the trait rather than the method)
951    ///
952    /// [inherent method]: struct.HCons.html#method.sculpt
953    fn sculpt(self) -> (Target, Self::Remainder);
954}
955
956/// Implementation for when the target is an empty HList (HNil)
957///
958/// Index type is HNil because we don't need an index for finding HNil
959impl<Source> Sculptor<HNil, HNil> for Source {
960    type Remainder = Source;
961
962    #[inline(always)]
963    fn sculpt(self) -> (HNil, Self::Remainder) {
964        (HNil, self)
965    }
966}
967
968/// Implementation for when we have a non-empty HCons target
969///
970/// Indices is HCons<IndexHead, IndexTail> here because the compiler is being asked to figure out the
971/// Index for Plucking the first item of type THead out of Self and the rest (IndexTail) is for the
972/// Plucker's remainder induce.
973impl<THead, TTail, SHead, STail, IndexHead, IndexTail>
974    Sculptor<HCons<THead, TTail>, HCons<IndexHead, IndexTail>> for HCons<SHead, STail>
975where
976    HCons<SHead, STail>: Plucker<THead, IndexHead>,
977    <HCons<SHead, STail> as Plucker<THead, IndexHead>>::Remainder: Sculptor<TTail, IndexTail>,
978{
979    type Remainder = <<HCons<SHead, STail> as Plucker<THead, IndexHead>>::Remainder as Sculptor<
980        TTail,
981        IndexTail,
982    >>::Remainder;
983
984    #[inline(always)]
985    fn sculpt(self) -> (HCons<THead, TTail>, Self::Remainder) {
986        let (p, r): (
987            THead,
988            <HCons<SHead, STail> as Plucker<THead, IndexHead>>::Remainder,
989        ) = self.pluck();
990        let (tail, tail_remainder): (TTail, Self::Remainder) = r.sculpt();
991        (HCons { head: p, tail }, tail_remainder)
992    }
993}
994
995impl IntoReverse for HNil {
996    type Output = HNil;
997    fn into_reverse(self) -> Self::Output {
998        self
999    }
1000}
1001
1002impl<H, Tail> IntoReverse for HCons<H, Tail>
1003where
1004    Tail: IntoReverse,
1005    <Tail as IntoReverse>::Output: Add<HCons<H, HNil>>,
1006{
1007    type Output = <<Tail as IntoReverse>::Output as Add<HCons<H, HNil>>>::Output;
1008
1009    fn into_reverse(self) -> Self::Output {
1010        self.tail.into_reverse()
1011            + HCons {
1012                head: self.head,
1013                tail: HNil,
1014            }
1015    }
1016}
1017
1018impl<P, H, Tail> HMappable<Poly<P>> for HCons<H, Tail>
1019where
1020    P: Func<H>,
1021    Tail: HMappable<Poly<P>>,
1022{
1023    type Output = HCons<<P as Func<H>>::Output, <Tail as HMappable<Poly<P>>>::Output>;
1024    fn map(self, poly: Poly<P>) -> Self::Output {
1025        HCons {
1026            head: P::call(self.head),
1027            tail: self.tail.map(poly),
1028        }
1029    }
1030}
1031
1032/// Trait for mapping over an HList
1033///
1034/// This trait is part of the implementation of the inherent method
1035/// [`HCons::map`]. Please see that method for more information.
1036///
1037/// You only need to import this trait when working with generic
1038/// HLists or Mappers of unknown type. If the type of everything is known,
1039/// then `list.map(f)` should "just work" even without the trait.
1040///
1041/// [`HCons::map`]: struct.HCons.html#method.map
1042pub trait HMappable<Mapper> {
1043    type Output;
1044
1045    /// Apply a function to each element of an HList.
1046    ///
1047    /// Please see the [inherent method] for more information.
1048    ///
1049    /// The only difference between that inherent method and this
1050    /// trait method is the location of the type parameters.
1051    /// (here, they are on the trait rather than the method)
1052    ///
1053    /// [inherent method]: struct.HCons.html#method.map
1054    fn map(self, mapper: Mapper) -> Self::Output;
1055}
1056
1057impl<F> HMappable<F> for HNil {
1058    type Output = HNil;
1059
1060    fn map(self, _: F) -> Self::Output {
1061        HNil
1062    }
1063}
1064
1065impl<F, R, H, Tail> HMappable<F> for HCons<H, Tail>
1066where
1067    F: Fn(H) -> R,
1068    Tail: HMappable<F>,
1069{
1070    type Output = HCons<R, <Tail as HMappable<F>>::Output>;
1071
1072    fn map(self, f: F) -> Self::Output {
1073        let HCons { head, tail } = self;
1074        HCons {
1075            head: f(head),
1076            tail: tail.map(f),
1077        }
1078    }
1079}
1080
1081impl<F, R, MapperTail, H, Tail> HMappable<HCons<F, MapperTail>> for HCons<H, Tail>
1082where
1083    F: FnOnce(H) -> R,
1084    Tail: HMappable<MapperTail>,
1085{
1086    type Output = HCons<R, <Tail as HMappable<MapperTail>>::Output>;
1087
1088    fn map(self, mapper: HCons<F, MapperTail>) -> Self::Output {
1089        let HCons { head, tail } = self;
1090        HCons {
1091            head: (mapper.head)(head),
1092            tail: tail.map(mapper.tail),
1093        }
1094    }
1095}
1096
1097/// Trait for zipping HLists
1098///
1099/// This trait is part of the implementation of the inherent method
1100/// [`HCons::zip`]. Please see that method for more information.
1101///
1102/// You only need to import this trait when working with generic
1103/// HLists of unknown type. If the type of everything is known,
1104/// then `list.zip(list2)` should "just work" even without the trait.
1105///
1106/// [`HCons::zip`]: struct.HCons.html#method.zip
1107pub trait HZippable<Other> {
1108    type Zipped: HList;
1109
1110    /// Zip this HList with another one.
1111    ///
1112    /// Please see the [inherent method] for more information.
1113    ///
1114    /// [inherent method]: struct.HCons.html#method.zip
1115    fn zip(self, other: Other) -> Self::Zipped;
1116}
1117
1118impl HZippable<HNil> for HNil {
1119    type Zipped = HNil;
1120    fn zip(self, _other: HNil) -> Self::Zipped {
1121        HNil
1122    }
1123}
1124
1125impl<H1, T1, H2, T2> HZippable<HCons<H2, T2>> for HCons<H1, T1>
1126where
1127    T1: HZippable<T2>,
1128{
1129    type Zipped = HCons<(H1, H2), T1::Zipped>;
1130    fn zip(self, other: HCons<H2, T2>) -> Self::Zipped {
1131        HCons {
1132            head: (self.head, other.head),
1133            tail: self.tail.zip(other.tail),
1134        }
1135    }
1136}
1137
1138/// Trait for performing a right fold over an HList
1139///
1140/// This trait is part of the implementation of the inherent method
1141/// [`HCons::foldr`]. Please see that method for more information.
1142///
1143/// You only need to import this trait when working with generic
1144/// HLists or Folders of unknown type. If the type of everything is known,
1145/// then `list.foldr(f, init)` should "just work" even without the trait.
1146///
1147/// [`HCons::foldr`]: struct.HCons.html#method.foldr
1148pub trait HFoldRightable<Folder, Init> {
1149    type Output;
1150
1151    /// Perform a right fold over an HList.
1152    ///
1153    /// Please see the [inherent method] for more information.
1154    ///
1155    /// The only difference between that inherent method and this
1156    /// trait method is the location of the type parameters.
1157    /// (here, they are on the trait rather than the method)
1158    ///
1159    /// [inherent method]: struct.HCons.html#method.foldr
1160    fn foldr(self, folder: Folder, i: Init) -> Self::Output;
1161}
1162
1163impl<F, Init> HFoldRightable<F, Init> for HNil {
1164    type Output = Init;
1165
1166    fn foldr(self, _: F, i: Init) -> Self::Output {
1167        i
1168    }
1169}
1170
1171impl<F, FolderHeadR, FolderTail, H, Tail, Init> HFoldRightable<HCons<F, FolderTail>, Init>
1172    for HCons<H, Tail>
1173where
1174    Tail: HFoldRightable<FolderTail, Init>,
1175    F: FnOnce(<Tail as HFoldRightable<FolderTail, Init>>::Output, H) -> FolderHeadR,
1176{
1177    type Output = FolderHeadR;
1178
1179    fn foldr(self, folder: HCons<F, FolderTail>, init: Init) -> Self::Output {
1180        let folded_tail = self.tail.foldr(folder.tail, init);
1181        (folder.head)(folded_tail, self.head)
1182    }
1183}
1184
1185impl<F, R, H, Tail, Init> HFoldRightable<F, Init> for HCons<H, Tail>
1186where
1187    Tail: foldr_owned::HFoldRightableOwned<F, Init>,
1188    F: Fn(<Tail as HFoldRightable<F, Init>>::Output, H) -> R,
1189{
1190    type Output = R;
1191
1192    fn foldr(self, folder: F, init: Init) -> Self::Output {
1193        foldr_owned::HFoldRightableOwned::real_foldr(self, folder, init).0
1194    }
1195}
1196
1197/// [`HFoldRightable`] inner mechanics for folding with a folder that needs to be owned.
1198pub mod foldr_owned {
1199    use super::{HCons, HFoldRightable, HNil};
1200
1201    /// A real `foldr` for the folder that must be owned to fold.
1202    ///
1203    /// Due to `HList` being a recursive struct and not linear array,
1204    /// the only way to fold it is recursive.
1205    ///
1206    /// However, there are differences in the `foldl` and `foldr` traversing
1207    /// the `HList`:
1208    ///
1209    /// 1. `foldl` calls `folder(head)` and then passes the ownership
1210    ///     of the folder to the next recursive call.
1211    /// 2. `foldr` passes the ownership of the folder to the next recursive call,
1212    ///     and then tries to call `folder(head)`; but the ownership is already gone!
1213    pub trait HFoldRightableOwned<Folder, Init>: HFoldRightable<Folder, Init> {
1214        fn real_foldr(self, folder: Folder, init: Init) -> (Self::Output, Folder);
1215    }
1216
1217    impl<F, Init> HFoldRightableOwned<F, Init> for HNil {
1218        fn real_foldr(self, f: F, i: Init) -> (Self::Output, F) {
1219            (i, f)
1220        }
1221    }
1222
1223    impl<F, H, Tail, Init> HFoldRightableOwned<F, Init> for HCons<H, Tail>
1224    where
1225        Self: HFoldRightable<F, Init>,
1226        Tail: HFoldRightableOwned<F, Init>,
1227        F: Fn(<Tail as HFoldRightable<F, Init>>::Output, H) -> Self::Output,
1228    {
1229        fn real_foldr(self, folder: F, init: Init) -> (Self::Output, F) {
1230            let (folded_tail, folder) = self.tail.real_foldr(folder, init);
1231            ((folder)(folded_tail, self.head), folder)
1232        }
1233    }
1234}
1235
1236impl<P, R, H, Tail, Init> HFoldRightable<Poly<P>, Init> for HCons<H, Tail>
1237where
1238    Tail: HFoldRightable<Poly<P>, Init>,
1239    P: Func<(<Tail as HFoldRightable<Poly<P>, Init>>::Output, H), Output = R>,
1240{
1241    type Output = R;
1242
1243    fn foldr(self, poly: Poly<P>, init: Init) -> Self::Output {
1244        let HCons { head, tail } = self;
1245        let folded_tail = tail.foldr(poly, init);
1246        P::call((folded_tail, head))
1247    }
1248}
1249
1250impl<'a> ToRef<'a> for HNil {
1251    type Output = HNil;
1252
1253    #[inline(always)]
1254    fn to_ref(&'a self) -> Self::Output {
1255        HNil
1256    }
1257}
1258
1259impl<'a, H, Tail> ToRef<'a> for HCons<H, Tail>
1260where
1261    H: 'a,
1262    Tail: ToRef<'a>,
1263{
1264    type Output = HCons<&'a H, <Tail as ToRef<'a>>::Output>;
1265
1266    #[inline(always)]
1267    fn to_ref(&'a self) -> Self::Output {
1268        HCons {
1269            head: &self.head,
1270            tail: self.tail.to_ref(),
1271        }
1272    }
1273}
1274
1275impl<'a> ToMut<'a> for HNil {
1276    type Output = HNil;
1277
1278    #[inline(always)]
1279    fn to_mut(&'a mut self) -> Self::Output {
1280        HNil
1281    }
1282}
1283
1284impl<'a, H, Tail> ToMut<'a> for HCons<H, Tail>
1285where
1286    H: 'a,
1287    Tail: ToMut<'a>,
1288{
1289    type Output = HCons<&'a mut H, <Tail as ToMut<'a>>::Output>;
1290
1291    #[inline(always)]
1292    fn to_mut(&'a mut self) -> Self::Output {
1293        HCons {
1294            head: &mut self.head,
1295            tail: self.tail.to_mut(),
1296        }
1297    }
1298}
1299
1300/// Trait for performing a left fold over an HList
1301///
1302/// This trait is part of the implementation of the inherent method
1303/// [`HCons::foldl`]. Please see that method for more information.
1304///
1305/// You only need to import this trait when working with generic
1306/// HLists or Mappers of unknown type. If the type of everything is known,
1307/// then `list.foldl(f, acc)` should "just work" even without the trait.
1308///
1309/// [`HCons::foldl`]: struct.HCons.html#method.foldl
1310pub trait HFoldLeftable<Folder, Acc> {
1311    type Output;
1312
1313    /// Perform a left fold over an HList.
1314    ///
1315    /// Please see the [inherent method] for more information.
1316    ///
1317    /// The only difference between that inherent method and this
1318    /// trait method is the location of the type parameters.
1319    /// (here, they are on the trait rather than the method)
1320    ///
1321    /// [inherent method]: struct.HCons.html#method.foldl
1322    fn foldl(self, folder: Folder, acc: Acc) -> Self::Output;
1323}
1324
1325impl<F, Acc> HFoldLeftable<F, Acc> for HNil {
1326    type Output = Acc;
1327
1328    fn foldl(self, _: F, acc: Acc) -> Self::Output {
1329        acc
1330    }
1331}
1332
1333impl<F, R, FTail, H, Tail, Acc> HFoldLeftable<HCons<F, FTail>, Acc> for HCons<H, Tail>
1334where
1335    Tail: HFoldLeftable<FTail, R>,
1336    F: FnOnce(Acc, H) -> R,
1337{
1338    type Output = <Tail as HFoldLeftable<FTail, R>>::Output;
1339
1340    fn foldl(self, folder: HCons<F, FTail>, acc: Acc) -> Self::Output {
1341        let HCons { head, tail } = self;
1342        tail.foldl(folder.tail, (folder.head)(acc, head))
1343    }
1344}
1345
1346impl<P, R, H, Tail, Acc> HFoldLeftable<Poly<P>, Acc> for HCons<H, Tail>
1347where
1348    Tail: HFoldLeftable<Poly<P>, R>,
1349    P: Func<(Acc, H), Output = R>,
1350{
1351    type Output = <Tail as HFoldLeftable<Poly<P>, R>>::Output;
1352
1353    fn foldl(self, poly: Poly<P>, acc: Acc) -> Self::Output {
1354        let HCons { head, tail } = self;
1355        let r = P::call((acc, head));
1356        tail.foldl(poly, r)
1357    }
1358}
1359
1360/// Implementation for folding over an HList using a single function that
1361/// can handle all cases
1362///
1363/// ```
1364/// # fn main() {
1365/// use frunk_core::hlist;
1366///
1367/// let h = hlist![1, 2, 3, 4, 5];
1368///
1369/// let r: isize = h.foldl(|acc, next| acc + next, 0);
1370/// assert_eq!(r, 15);
1371/// # }
1372/// ```
1373impl<F, H, Tail, Acc> HFoldLeftable<F, Acc> for HCons<H, Tail>
1374where
1375    Tail: HFoldLeftable<F, Acc>,
1376    F: Fn(Acc, H) -> Acc,
1377{
1378    type Output = <Tail as HFoldLeftable<F, Acc>>::Output;
1379
1380    fn foldl(self, f: F, acc: Acc) -> Self::Output {
1381        let HCons { head, tail } = self;
1382        let acc = f(acc, head);
1383        tail.foldl(f, acc)
1384    }
1385}
1386
1387/// Trait for transforming an HList into a nested tuple.
1388///
1389/// This trait is part of the implementation of the inherent method
1390/// [`HCons::into_tuple2`]. Please see that method for more information.
1391///
1392/// This operation is not useful in generic contexts, so it is unlikely
1393/// that you should ever need to import this trait. Do not worry;
1394/// if you have an HList of known type, then `list.into_tuple2()`
1395/// should "just work," even without the trait.
1396///
1397/// [`HCons::into_tuple2`]: struct.HCons.html#method.into_tuple2
1398pub trait IntoTuple2 {
1399    /// The 0 element in the output tuple
1400    type HeadType;
1401
1402    /// The 1 element in the output tuple
1403    type TailOutput;
1404
1405    /// Turns an HList into nested Tuple2s, which are less troublesome to pattern match
1406    /// and have a nicer type signature.
1407    ///
1408    /// Please see the [inherent method] for more information.
1409    ///
1410    /// [inherent method]: struct.HCons.html#method.into_tuple2
1411    fn into_tuple2(self) -> (Self::HeadType, Self::TailOutput);
1412}
1413
1414impl<T1, T2> IntoTuple2 for HCons<T1, HCons<T2, HNil>> {
1415    type HeadType = T1;
1416    type TailOutput = T2;
1417
1418    fn into_tuple2(self) -> (Self::HeadType, Self::TailOutput) {
1419        (self.head, self.tail.head)
1420    }
1421}
1422
1423impl<T, Tail> IntoTuple2 for HCons<T, Tail>
1424where
1425    Tail: IntoTuple2,
1426{
1427    type HeadType = T;
1428    type TailOutput = (
1429        <Tail as IntoTuple2>::HeadType,
1430        <Tail as IntoTuple2>::TailOutput,
1431    );
1432
1433    fn into_tuple2(self) -> (Self::HeadType, Self::TailOutput) {
1434        (self.head, self.tail.into_tuple2())
1435    }
1436}
1437
1438#[cfg(feature = "alloc")]
1439#[allow(clippy::from_over_into)]
1440impl<H, Tail> Into<Vec<H>> for HCons<H, Tail>
1441where
1442    Tail: Into<Vec<H>> + HList,
1443{
1444    fn into(self) -> Vec<H> {
1445        let h = self.head;
1446        let t = self.tail;
1447        let mut v = Vec::with_capacity(<Self as HList>::LEN);
1448        v.push(h);
1449        let mut t_vec: Vec<H> = t.into();
1450        v.append(&mut t_vec);
1451        v
1452    }
1453}
1454
1455#[cfg(feature = "alloc")]
1456#[allow(clippy::from_over_into)]
1457impl<T> Into<Vec<T>> for HNil {
1458    fn into(self) -> Vec<T> {
1459        Vec::with_capacity(0)
1460    }
1461}
1462
1463impl Default for HNil {
1464    fn default() -> Self {
1465        HNil
1466    }
1467}
1468
1469impl<T: Default, Tail: Default + HList> Default for HCons<T, Tail> {
1470    fn default() -> Self {
1471        h_cons(T::default(), Tail::default())
1472    }
1473}
1474
1475/// Indexed type conversions of `T -> Self` with index `I`.
1476/// This is a generalized version of `From` which for example allows the caller
1477/// to use default values for parts of `Self` and thus "fill in the blanks".
1478///
1479/// `LiftFrom` is the reciprocal of `LiftInto`.
1480///
1481/// ```
1482/// # fn main() {
1483/// use frunk::lift_from;
1484/// use frunk::prelude::*;
1485/// use frunk_core::{HList, hlist};
1486///
1487/// type H = HList![(), usize, f64, (), bool];
1488///
1489/// let x = H::lift_from(42.0);
1490/// assert_eq!(x, hlist![(), 0, 42.0, (), false]);
1491///
1492/// let x: H = lift_from(true);
1493/// assert_eq!(x, hlist![(), 0, 0.0, (), true]);
1494/// # }
1495/// ```
1496pub trait LiftFrom<T, I> {
1497    /// Performs the indexed conversion.
1498    fn lift_from(part: T) -> Self;
1499}
1500
1501/// Free function version of `LiftFrom::lift_from`.
1502pub fn lift_from<I, T, PF: LiftFrom<T, I>>(part: T) -> PF {
1503    PF::lift_from(part)
1504}
1505
1506/// An indexed conversion that consumes `self`, and produces a `T`. To produce
1507/// `T`, the index `I` may be used to for example "fill in the blanks".
1508/// `LiftInto` is the reciprocal of `LiftFrom`.
1509///
1510/// ```
1511/// # fn main() {
1512/// use frunk::prelude::*;
1513/// use frunk_core::{HList, hlist};
1514///
1515/// type H = HList![(), usize, f64, (), bool];
1516///
1517/// // Type inference works as expected:
1518/// let x: H = 1337.lift_into();
1519/// assert_eq!(x, hlist![(), 1337, 0.0, (), false]);
1520///
1521/// // Sublists:
1522/// let x: H = hlist![(), true].lift_into();
1523/// assert_eq!(x, hlist![(), 0, 0.0, (), true]);
1524///
1525/// let x: H = hlist![3.0, ()].lift_into();
1526/// assert_eq!(x, hlist![(), 0, 3.0, (), false]);
1527///
1528/// let x: H = hlist![(), 1337].lift_into();
1529/// assert_eq!(x, hlist![(), 1337, 0.0, (), false]);
1530///
1531/// let x: H = hlist![(), 1337, 42.0, (), true].lift_into();
1532/// assert_eq!(x, hlist![(), 1337, 42.0, (), true]);
1533/// # }
1534/// ```
1535pub trait LiftInto<T, I> {
1536    /// Performs the indexed conversion.
1537    fn lift_into(self) -> T;
1538}
1539
1540impl<T, U, I> LiftInto<U, I> for T
1541where
1542    U: LiftFrom<T, I>,
1543{
1544    fn lift_into(self) -> U {
1545        LiftFrom::lift_from(self)
1546    }
1547}
1548
1549impl<T, Tail> LiftFrom<T, Here> for HCons<T, Tail>
1550where
1551    Tail: Default + HList,
1552{
1553    fn lift_from(part: T) -> Self {
1554        h_cons(part, Tail::default())
1555    }
1556}
1557
1558impl<Head, Tail, ValAtIx, TailIx> LiftFrom<ValAtIx, There<TailIx>> for HCons<Head, Tail>
1559where
1560    Head: Default,
1561    Tail: HList + LiftFrom<ValAtIx, TailIx>,
1562{
1563    fn lift_from(part: ValAtIx) -> Self {
1564        h_cons(Head::default(), Tail::lift_from(part))
1565    }
1566}
1567
1568impl<Prefix, Suffix> LiftFrom<Prefix, Suffixed<Suffix>> for <Prefix as Add<Suffix>>::Output
1569where
1570    Prefix: HList + Add<Suffix>,
1571    Suffix: Default,
1572{
1573    fn lift_from(part: Prefix) -> Self {
1574        part + Suffix::default()
1575    }
1576}
1577
1578#[cfg(test)]
1579mod tests {
1580    use super::*;
1581
1582    use alloc::vec;
1583
1584    #[test]
1585    fn test_hcons() {
1586        let hlist1 = h_cons(1, HNil);
1587        let (h, _) = hlist1.pop();
1588        assert_eq!(h, 1);
1589
1590        let hlist2 = h_cons("hello", h_cons(1, HNil));
1591        let (h2, tail2) = hlist2.pop();
1592        let (h1, _) = tail2.pop();
1593        assert_eq!(h2, "hello");
1594        assert_eq!(h1, 1);
1595    }
1596
1597    struct HasHList<T: HList>(T);
1598
1599    #[test]
1600    fn test_contained_list() {
1601        let c = HasHList(h_cons(1, HNil));
1602        let retrieved = c.0;
1603        assert_eq!(retrieved.len(), 1);
1604        let new_list = h_cons(2, retrieved);
1605        assert_eq!(new_list.len(), 2);
1606    }
1607
1608    #[test]
1609    fn test_pluck() {
1610        let h = hlist![1, "hello", true, 42f32];
1611        let (t, r): (f32, _) = h.pluck();
1612        assert_eq!(t, 42f32);
1613        assert_eq!(r, hlist![1, "hello", true])
1614    }
1615
1616    #[test]
1617    fn test_hlist_macro() {
1618        assert_eq!(hlist![], HNil);
1619        let h: HList!(i32, &str, i32) = hlist![1, "2", 3];
1620        let (h1, tail1) = h.pop();
1621        assert_eq!(h1, 1);
1622        assert_eq!(tail1, hlist!["2", 3]);
1623        let (h2, tail2) = tail1.pop();
1624        assert_eq!(h2, "2");
1625        assert_eq!(tail2, hlist![3]);
1626        let (h3, tail3) = tail2.pop();
1627        assert_eq!(h3, 3);
1628        assert_eq!(tail3, HNil);
1629    }
1630
1631    #[test]
1632    #[allow(non_snake_case)]
1633    fn test_Hlist_macro() {
1634        let h1: HList!(i32, &str, i32) = hlist![1, "2", 3];
1635        let h2: HList!(i32, &str, i32,) = hlist![1, "2", 3];
1636        let h3: HList!(i32) = hlist![1];
1637        let h4: HList!(i32,) = hlist![1,];
1638        assert_eq!(h1, h2);
1639        assert_eq!(h3, h4);
1640    }
1641
1642    #[test]
1643    fn test_pattern_matching() {
1644        let hlist_pat!(one1) = hlist!["one"];
1645        assert_eq!(one1, "one");
1646        let hlist_pat!(one2,) = hlist!["one"];
1647        assert_eq!(one2, "one");
1648
1649        let h = hlist![5, 3.2f32, true, "blue"];
1650        let hlist_pat!(five, float, right, s) = h;
1651        assert_eq!(five, 5);
1652        assert_eq!(float, 3.2f32);
1653        assert!(right);
1654        assert_eq!(s, "blue");
1655
1656        let h2 = hlist![13.5f32, "hello", Some(41)];
1657        let hlist_pat![a, b, c,] = h2;
1658        assert_eq!(a, 13.5f32);
1659        assert_eq!(b, "hello");
1660        assert_eq!(c, Some(41));
1661    }
1662
1663    #[test]
1664    fn test_add() {
1665        let h1 = hlist![true, "hi"];
1666        let h2 = hlist![1, 32f32];
1667        let combined = h1 + h2;
1668        assert_eq!(combined, hlist![true, "hi", 1, 32f32])
1669    }
1670
1671    #[test]
1672    fn test_into_reverse() {
1673        let h1 = hlist![true, "hi"];
1674        let h2 = hlist![1, 32f32];
1675        assert_eq!(h1.into_reverse(), hlist!["hi", true]);
1676        assert_eq!(h2.into_reverse(), hlist![32f32, 1]);
1677    }
1678
1679    #[test]
1680    fn test_foldr_consuming() {
1681        let h = hlist![1, false, 42f32];
1682        let folded = h.foldr(
1683            hlist![
1684                |acc, i| i + acc,
1685                |acc, _| if acc > 42f32 { 9000 } else { 0 },
1686                |acc, f| f + acc,
1687            ],
1688            1f32,
1689        );
1690        assert_eq!(folded, 9001)
1691    }
1692
1693    #[test]
1694    fn test_single_func_foldr_consuming() {
1695        let h = hlist![1, 2, 3];
1696        let folded = h.foldr(&|acc, i| i * acc, 1);
1697        assert_eq!(folded, 6)
1698    }
1699
1700    #[test]
1701    fn test_foldr_non_consuming() {
1702        let h = hlist![1, false, 42f32];
1703        let folder = hlist![
1704            |acc, &i| i + acc,
1705            |acc, &_| if acc > 42f32 { 9000 } else { 0 },
1706            |acc, &f| f + acc
1707        ];
1708        let folded = h.to_ref().foldr(folder, 1f32);
1709        assert_eq!(folded, 9001)
1710    }
1711
1712    #[test]
1713    fn test_poly_foldr_consuming() {
1714        trait Dummy {
1715            fn dummy(&self) -> i32 {
1716                1
1717            }
1718        }
1719        impl<T: ?Sized> Dummy for T {}
1720
1721        struct Dummynator;
1722        impl<T: Dummy, I: IntoIterator<Item = T>> Func<(i32, I)> for Dummynator {
1723            type Output = i32;
1724            fn call(args: (i32, I)) -> Self::Output {
1725                let (init, i) = args;
1726                i.into_iter().fold(init, |init, x| init + x.dummy())
1727            }
1728        }
1729
1730        let h = hlist![0..10, 0..=10, &[0, 1, 2], &['a', 'b', 'c']];
1731        assert_eq!(
1732            h.foldr(Poly(Dummynator), 0),
1733            (0..10)
1734                .map(|d| d.dummy())
1735                .chain((0..=10).map(|d| d.dummy()))
1736                .chain([0_i32, 1, 2].iter().map(|d| d.dummy()))
1737                .chain(['a', 'b', 'c'].iter().map(|d| d.dummy()))
1738                .sum()
1739        );
1740    }
1741
1742    #[test]
1743    fn test_foldl_consuming() {
1744        let h = hlist![1, false, 42f32];
1745        let folded = h.foldl(
1746            hlist![
1747                |acc, i| i + acc,
1748                |acc, b: bool| if !b && acc > 42 { 9000f32 } else { 0f32 },
1749                |acc, f| f + acc,
1750            ],
1751            1,
1752        );
1753        assert_eq!(42f32, folded)
1754    }
1755
1756    #[test]
1757    fn test_foldl_non_consuming() {
1758        let h = hlist![1, false, 42f32];
1759        let folded = h.to_ref().foldl(
1760            hlist![
1761                |acc, &i| i + acc,
1762                |acc, b: &bool| if !b && acc > 42 { 9000f32 } else { 0f32 },
1763                |acc, &f| f + acc,
1764            ],
1765            1,
1766        );
1767        assert_eq!(42f32, folded);
1768        assert_eq!((&h.head), &1);
1769    }
1770
1771    #[test]
1772    fn test_poly_foldl_consuming() {
1773        trait Dummy {
1774            fn dummy(&self) -> i32 {
1775                1
1776            }
1777        }
1778        impl<T: ?Sized> Dummy for T {}
1779
1780        struct Dummynator;
1781        impl<T: Dummy, I: IntoIterator<Item = T>> Func<(i32, I)> for Dummynator {
1782            type Output = i32;
1783            fn call(args: (i32, I)) -> Self::Output {
1784                let (acc, i) = args;
1785                i.into_iter().fold(acc, |acc, x| acc + x.dummy())
1786            }
1787        }
1788
1789        let h = hlist![0..10, 0..=10, &[0, 1, 2], &['a', 'b', 'c']];
1790        assert_eq!(
1791            h.foldl(Poly(Dummynator), 0),
1792            (0..10)
1793                .map(|d| d.dummy())
1794                .chain((0..=10).map(|d| d.dummy()))
1795                .chain([0_i32, 1, 2].iter().map(|d| d.dummy()))
1796                .chain(['a', 'b', 'c'].iter().map(|d| d.dummy()))
1797                .sum()
1798        );
1799    }
1800
1801    #[test]
1802    fn test_map_consuming() {
1803        let h = hlist![9000, "joe", 41f32];
1804        let mapped = h.map(hlist![|n| n + 1, |s| s, |f| f + 1f32]);
1805        assert_eq!(mapped, hlist![9001, "joe", 42f32]);
1806    }
1807
1808    #[test]
1809    fn test_poly_map_consuming() {
1810        let h = hlist![9000, "joe", 41f32, "schmoe", 50];
1811        impl Func<i32> for P {
1812            type Output = bool;
1813            fn call(args: i32) -> Self::Output {
1814                args > 100
1815            }
1816        }
1817        impl<'a> Func<&'a str> for P {
1818            type Output = usize;
1819            fn call(args: &'a str) -> Self::Output {
1820                args.len()
1821            }
1822        }
1823        impl Func<f32> for P {
1824            type Output = &'static str;
1825            fn call(_: f32) -> Self::Output {
1826                "dummy"
1827            }
1828        }
1829        struct P;
1830        assert_eq!(h.map(Poly(P)), hlist![true, 3, "dummy", 6, false]);
1831    }
1832
1833    #[test]
1834    fn test_poly_map_non_consuming() {
1835        let h = hlist![9000, "joe", 41f32, "schmoe", 50];
1836        impl<'a> Func<&'a i32> for P {
1837            type Output = bool;
1838            fn call(args: &'a i32) -> Self::Output {
1839                *args > 100
1840            }
1841        }
1842        impl<'a> Func<&'a &'a str> for P {
1843            type Output = usize;
1844            fn call(args: &'a &'a str) -> Self::Output {
1845                args.len()
1846            }
1847        }
1848        impl<'a> Func<&'a f32> for P {
1849            type Output = &'static str;
1850            fn call(_: &'a f32) -> Self::Output {
1851                "dummy"
1852            }
1853        }
1854        struct P;
1855        assert_eq!(h.to_ref().map(Poly(P)), hlist![true, 3, "dummy", 6, false]);
1856    }
1857
1858    #[test]
1859    fn test_map_single_func_consuming() {
1860        let h = hlist![9000, 9001, 9002];
1861        let mapped = h.map(|v| v + 1);
1862        assert_eq!(mapped, hlist![9001, 9002, 9003]);
1863    }
1864
1865    #[test]
1866    fn test_map_single_func_non_consuming() {
1867        let h = hlist![9000, 9001, 9002];
1868        let mapped = h.to_ref().map(|v| v + 1);
1869        assert_eq!(mapped, hlist![9001, 9002, 9003]);
1870    }
1871
1872    #[test]
1873    fn test_map_non_consuming() {
1874        let h = hlist![9000, "joe", 41f32];
1875        let mapped = h.to_ref().map(hlist![|&n| n + 1, |&s| s, |&f| f + 1f32]);
1876        assert_eq!(mapped, hlist![9001, "joe", 42f32]);
1877    }
1878
1879    #[test]
1880    fn test_zip_easy() {
1881        let h1 = hlist![9000, "joe", 41f32];
1882        let h2 = hlist!["joe", 9001, 42f32];
1883        let zipped = h1.zip(h2);
1884        assert_eq!(
1885            zipped,
1886            hlist![(9000, "joe"), ("joe", 9001), (41f32, 42f32),]
1887        );
1888    }
1889
1890    #[test]
1891    fn test_zip_composes() {
1892        let h1 = hlist![1, "1", 1.0];
1893        let h2 = hlist![2, "2", 2.0];
1894        let h3 = hlist![3, "3", 3.0];
1895        let zipped = h1.zip(h2).zip(h3);
1896        assert_eq!(
1897            zipped,
1898            hlist![((1, 2), 3), (("1", "2"), "3"), ((1.0, 2.0), 3.0)],
1899        );
1900    }
1901
1902    #[test]
1903    fn test_sculpt() {
1904        let h = hlist![9000, "joe", 41f32];
1905        let (reshaped, remainder): (HList!(f32, i32), _) = h.sculpt();
1906        assert_eq!(reshaped, hlist![41f32, 9000]);
1907        assert_eq!(remainder, hlist!["joe"])
1908    }
1909
1910    #[test]
1911    fn test_len_const() {
1912        assert_eq!(<HList![usize, &str, f32] as HList>::LEN, 3);
1913    }
1914
1915    #[test]
1916    fn test_single_func_foldl_consuming() {
1917        use std::collections::HashMap;
1918
1919        let h = hlist![
1920            ("one", 1),
1921            ("two", 2),
1922            ("three", 3),
1923            ("four", 4),
1924            ("five", 5),
1925        ];
1926        let r = h.foldl(
1927            |mut acc: HashMap<&'static str, isize>, (k, v)| {
1928                acc.insert(k, v);
1929                acc
1930            },
1931            HashMap::with_capacity(5),
1932        );
1933        let expected: HashMap<_, _> = {
1934            vec![
1935                ("one", 1),
1936                ("two", 2),
1937                ("three", 3),
1938                ("four", 4),
1939                ("five", 5),
1940            ]
1941            .into_iter()
1942            .collect()
1943        };
1944        assert_eq!(r, expected);
1945    }
1946
1947    #[test]
1948    fn test_single_func_foldl_non_consuming() {
1949        let h = hlist![1, 2, 3, 4, 5];
1950        let r: isize = h.to_ref().foldl(|acc, &next| acc + next, 0isize);
1951        assert_eq!(r, 15);
1952    }
1953
1954    #[test]
1955    #[cfg(feature = "alloc")]
1956    fn test_into_vec() {
1957        let h = hlist![1, 2, 3, 4, 5];
1958        let as_vec: Vec<_> = h.into();
1959        assert_eq!(as_vec, vec![1, 2, 3, 4, 5])
1960    }
1961
1962    #[test]
1963    fn test_lift() {
1964        type H = HList![(), usize, f64, (), bool];
1965
1966        // Ensure type inference works as expected first:
1967        let x: H = 1337.lift_into();
1968        assert_eq!(x, hlist![(), 1337, 0.0, (), false]);
1969
1970        let x = H::lift_from(42.0);
1971        assert_eq!(x, hlist![(), 0, 42.0, (), false]);
1972
1973        let x: H = lift_from(true);
1974        assert_eq!(x, hlist![(), 0, 0.0, (), true]);
1975
1976        // Sublists:
1977        let x: H = hlist![(), true].lift_into();
1978        assert_eq!(x, hlist![(), 0, 0.0, (), true]);
1979
1980        let x: H = hlist![3.0, ()].lift_into();
1981        assert_eq!(x, hlist![(), 0, 3.0, (), false]);
1982
1983        let x: H = hlist![(), 1337].lift_into();
1984        assert_eq!(x, hlist![(), 1337, 0.0, (), false]);
1985
1986        let x: H = hlist![(), 1337, 42.0, (), true].lift_into();
1987        assert_eq!(x, hlist![(), 1337, 42.0, (), true]);
1988    }
1989
1990    #[test]
1991    fn test_hcons_extend_hnil() {
1992        let first = hlist![0];
1993        let second = hlist![];
1994
1995        assert_eq!(first.extend(second), hlist![0]);
1996    }
1997
1998    #[test]
1999    fn test_hnil_extend_hcons() {
2000        let first = hlist![];
2001        let second = hlist![0];
2002
2003        assert_eq!(first.extend(second), hlist![0]);
2004    }
2005
2006    #[test]
2007    fn test_hnil_extend_hnil() {
2008        let first = hlist![];
2009        let second = hlist![];
2010
2011        assert_eq!(first.extend(second), hlist![]);
2012    }
2013}