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
use crate::prelude::*;

/// [`FoldableOnce`] for indexed data structures
pub trait FoldableOnceIndexed<F, Idx, A>
  where Self: FoldableOnce<F, A>,
        F: HKT1<T<A> = Self>
{
  /// Fold the data structure
  fn fold1_idx<B, BAB>(self, f: BAB, b: B) -> B
    where BAB: F3Once<B, Idx, A, Ret = B>;

  /// Fold the data structure
  fn fold1_idx_ref<'a, B, BAB>(&'a self, f: BAB, b: B) -> B
    where BAB: F3Once<B, &'a Idx, &'a A, Ret = B>,
          A: 'a,
          Idx: 'a;
}

/// [`Foldable`], but specialized to know at compile-time
/// that the reducing function will only be called one time.
pub trait FoldableOnce<F, A>
  where F: HKT1<T<A> = Self>
{
  /// Fold the data structure
  fn fold1<B, BAB>(self, f: BAB, b: B) -> B
    where BAB: F2Once<B, A, Ret = B>;

  /// Fold the data structure
  fn fold1_ref<'a, B, BAB>(&'a self, f: BAB, b: B) -> B
    where BAB: F2Once<B, &'a A, Ret = B>,
          A: 'a;

  /// Unwrap the data structure, using a provided default value if empty
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// assert_eq!(Some("a").get_or("b"), "a");
  /// assert_eq!(None.get_or("b"), "b");
  /// ```
  fn get_or(self, a: A) -> A
    where Self: Sized
  {
    self.fold1(|_, a| a, a)
  }

  /// Unwrap the data structure, using [`Default::default`] if empty
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// assert_eq!(Some(format!("a")).get_or_default(), format!("a"));
  /// assert_eq!(Option::<String>::None.get_or_default(), String::new());
  /// ```
  fn get_or_default(self) -> A
    where Self: Sized,
          A: Default
  {
    self.get_or(Default::default())
  }
}

/// [`Foldable`] for indexed collections
pub trait FoldableIndexed<F, Idx, A>
  where F: HKT1<T<A> = Self>,
        Self: Foldable<F, A>,
        Idx: Clone
{
  /// Fold the data structure from left -> right
  fn foldl_idx<B, BAB>(self, f: BAB, b: B) -> B
    where BAB: F3<B, Idx, A, Ret = B>;

  /// Fold the data structure from right -> left
  fn foldr_idx<B, ABB>(self, f: ABB, b: B) -> B
    where ABB: F3<Idx, A, B, Ret = B>;

  /// Fold the data structure from left -> right
  fn foldl_idx_ref<'a, B, BAB>(&'a self, f: BAB, b: B) -> B
    where BAB: F3<B, Idx, &'a A, Ret = B>,
          A: 'a,
          Idx: 'a;

  /// Fold the data structure from right -> left
  fn foldr_idx_ref<'a, B, ABB>(&'a self, f: ABB, b: B) -> B
    where ABB: F3<Idx, &'a A, B, Ret = B>,
          A: 'a,
          Idx: 'a;
}

/// Foldable represents data structures which can be collapsed by
/// starting with an initial value `B`, then a function that accumulates
/// `A`s into `B`.
///
/// # Examples
/// ## `fold` instead of `map` followed by `unwrap_or_else`
/// ```
/// use naan::prelude::*;
///
/// assert_eq!(Some(10).map(|a| i32::max(a, 20)).unwrap_or(20), 20);
///
/// assert_eq!(Some(10).foldl(i32::max, 20), 20);
/// assert_eq!(Some(10).foldl(i32::max, 1), 10);
/// assert_eq!(None.foldl(i32::max, 1), 1);
/// ```
///
/// ## Collapsing a collection to a single value
/// ```
/// use naan::prelude::*;
///
/// let ns = vec![4usize, 8, 10, 12];
///
/// let sum = ns.clone().foldl(|sum, cur| sum + cur, 0);
/// let product = ns.clone().foldl(|sum, cur| sum * cur, 1);
///
/// assert_eq!(sum, 34);
/// assert_eq!(product, 3840);
/// ```
///
/// # Picking a winning element from a collection
/// ```
/// use naan::prelude::*;
///
/// fn is_prime(n: usize) -> bool {
///   // <snip>
///   # false
/// }
///
/// let ns = vec![4usize, 8, 10, 12];
///
/// let smallest = ns.clone()
///                  .foldl(|largest: Option<usize>, cur| Some(largest.foldl(usize::min, cur)),
///                         None);
///
/// let largest = ns.clone()
///                 .foldl(|largest: Option<usize>, cur| Some(largest.foldl(usize::max, cur)),
///                        None);
///
/// let largest_prime =
///   ns.clone().foldl(|largest_p: Option<usize>, cur| {
///                      largest_p.foldl(|a: Option<usize>, p: usize| a.fmap(|a| usize::max(a, p)),
///                                      Some(cur).filter(|n| is_prime(*n)))
///                    },
///                    None);
///
/// assert_eq!(largest, Some(12));
/// assert_eq!(smallest, Some(4));
/// assert_eq!(largest_prime, None);
/// ```
pub trait Foldable<F, A>
  where F: HKT1<T<A> = Self>
{
  /// Fold the data structure from left -> right
  fn foldl<B, BAB>(self, f: BAB, b: B) -> B
    where BAB: F2<B, A, Ret = B>;

  /// Fold the data structure from right -> left
  fn foldr<B, ABB>(self, f: ABB, b: B) -> B
    where ABB: F2<A, B, Ret = B>;

  /// Fold the data structure from left -> right
  fn foldl_ref<'a, B, BAB>(&'a self, f: BAB, b: B) -> B
    where BAB: F2<B, &'a A, Ret = B>,
          A: 'a;

  /// Fold the data structure from right -> left
  fn foldr_ref<'a, B, ABB>(&'a self, f: ABB, b: B) -> B
    where ABB: F2<&'a A, B, Ret = B>,
          A: 'a;

  /// Fold the data structure, accumulating the values into a [`Monoid`].
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// let nums = vec![0u8, 1, 2];
  ///
  /// assert_eq!(nums.fold_map(|n: u8| format!("{n}")), format!("012"));
  /// ```
  fn fold_map<AB, B>(self, f: AB) -> B
    where Self: Sized,
          AB: F1<A, Ret = B>,
          B: Monoid
  {
    self.foldl(|b, a| B::append(b, f.call(a)), B::identity())
  }

  /// Accumulate the values in the data structure into a [`Monoid`].
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// let strings = vec![format!("a"), format!("b"), format!("c")];
  ///
  /// assert_eq!(strings.fold(), format!("abc"));
  /// ```
  fn fold(self) -> A
    where Self: Sized,
          A: Monoid
  {
    #[inline(always)]
    fn identity<T>(t: T) -> T {
      t
    }
    self.fold_map(identity)
  }

  /// [`fold`](Foldable::fold) the elements into `A` when `A` is [`Monoid`],
  /// inserting a separator between adjacent elements.
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// let strings = vec![format!("a"), format!("b"), format!("c")];
  ///
  /// assert_eq!(strings.intercalate(format!(", ")), format!("a, b, c"));
  /// ```
  fn intercalate(self, sep: A) -> A
    where Self: Sized,
          A: Monoid + Clone
  {
    struct Acc<A> {
      is_first: bool,
      acc: A,
    }

    self.foldl(|Acc { is_first, acc }: Acc<A>, a| {
                 if is_first {
                   Acc { is_first: false,
                         acc: a }
                 } else {
                   Acc { is_first: false,
                         acc: acc.append(sep.clone()).append(a) }
                 }
               },
               Acc::<A> { is_first: true,
                          acc: A::identity() })
        .acc
  }

  /// Test if the structure contains a value `a`
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// let strings = vec![format!("a"), format!("b"), format!("c")];
  ///
  /// assert_eq!(strings.contains(&format!("a")), true);
  /// assert_eq!(strings.contains(&format!("d")), false);
  /// ```
  fn contains<'a>(&'a self, a: &'a A) -> bool
    where &'a A: PartialEq,
          A: 'a
  {
    self.any(|cur| cur == a)
  }

  /// Test if the structure does not contain a value `a`
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// let strings = vec![format!("a"), format!("b"), format!("c")];
  ///
  /// assert_eq!(strings.not_contains(&format!("a")), false);
  /// assert_eq!(strings.not_contains(&format!("d")), true);
  /// ```
  fn not_contains<'a>(&'a self, a: &'a A) -> bool
    where &'a A: PartialEq,
          A: 'a
  {
    !self.contains(a)
  }

  /// Test if any element in the structure satisfies a predicate `f`
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// let strings = vec![format!("ab"), format!("cde")];
  ///
  /// assert_eq!(strings.any(|s: &String| s.len() > 2), true);
  /// ```
  fn any<'a, P>(&'a self, f: P) -> bool
    where P: F1<&'a A, Ret = bool>,
          A: 'a
  {
    self.foldl_ref(|pass: bool, cur| if !pass { f.call(cur) } else { true },
                   false)
  }

  /// Test if every element in the structure satisfies a predicate `f`
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// let strings = vec![format!("ab"), format!("cde")];
  ///
  /// assert_eq!(strings.all(|s: &String| s.len() < 4), true);
  /// ```
  fn all<'a, P>(&'a self, f: P) -> bool
    where P: F1<&'a A, Ret = bool>,
          A: 'a
  {
    self.foldl_ref(|pass: bool, cur| pass && f.call(cur), true)
  }

  /// Get the number of elements contained within the structure
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// assert_eq!(Vec::<()>::new().length(), 0);
  /// assert_eq!(vec![(), (), ()].length(), 3);
  /// ```
  fn length(&self) -> usize {
    self.foldl_ref(|n: usize, _| n + 1, 0usize)
  }

  /// Test if the structure is empty
  ///
  /// ```
  /// use naan::prelude::*;
  ///
  /// assert_eq!(Vec::<()>::new().is_empty(), true);
  /// assert_eq!(vec![()].is_empty(), false);
  /// ```
  fn is_empty(&self) -> bool {
    self.length() == 0
  }

  /// Fold values until a match is found
  fn find_map<AB, B>(self, f: AB) -> Option<B>
    where Self: Sized,
          AB: F1<A, Ret = Option<B>>
  {
    self.foldl(|found: Option<B>, a| found.fmap(Some).get_or(f.call(a)),
               None)
  }

  /// Fold values until a match is found
  fn find<P>(self, f: P) -> Option<A>
    where Self: Sized,
          P: for<'a> F1<&'a A, Ret = bool>
  {
    self.find_map(|a| Some(a).filter(|a| f.call(a)))
  }
}