fera_fun/lib.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5#![doc(html_root_url="https://docs.rs/fera-fun/0.1.0/")]
6
7//! Free functions for fun programming.
8//!
9//! This crate can be used through [`fera`] crate.
10//!
11//! [`fera`]: https://docs.rs/fera
12
13use std::borrow::Borrow;
14use std::collections::HashSet;
15use std::hash::Hash;
16
17/// Returns the first item of an iterator.
18///
19/// # Panics
20///
21/// If there is no first item.
22///
23/// # Examples
24///
25/// ```
26/// use fera_fun::first;
27///
28/// assert_eq!(&4, first(&[4, 3, 8]));
29/// assert_eq!(2, first(2..));
30/// ```
31pub fn first<I>(iter: I) -> I::Item
32 where I: IntoIterator
33{
34 iter.into_iter().next().unwrap()
35}
36
37/// Returns the first position of an item of an iterator or `None` if the iterator does not
38/// produces the item.
39///
40/// ```
41/// use fera_fun::position_of;
42///
43/// assert_eq!(Some(1), position_of(&[0, 3, 3, 0, 5], &3));
44/// ```
45pub fn position_of<I, T>(iter: I, item: &T) -> Option<usize>
46 where I: IntoIterator,
47 I::Item: Borrow<T>,
48 T: PartialEq
49{
50 iter.into_iter()
51 .position(|x| x.borrow() == item)
52}
53
54/// Returns the last position of the maximum element of a non empty iterator or `None` if iterator
55/// is empty.
56///
57/// ```
58/// use fera_fun::position_max_by_key;
59///
60/// assert_eq!(Some(4), position_max_by_key(&[0i32, 3, -5, 0, 5], |x| x.abs()));
61/// ```
62pub fn position_max_by_key<I, F, X>(iter: I, mut f: F) -> Option<usize>
63 where I: IntoIterator,
64 X: Ord,
65 F: FnMut(&I::Item) -> X
66{
67 iter.into_iter()
68 .enumerate()
69 .max_by_key(|x| f(&x.1))
70 .map(|x| x.0)
71}
72
73/// Returns the first position of the minimum element of a non empty iterator or `None` if iterator
74/// is empty.
75///
76/// ```
77/// use fera_fun::position_min_by_key;
78///
79/// assert_eq!(Some(0), position_min_by_key(&[0i32, 3, -5, 0, 5], |x| x.abs()));
80/// ```
81pub fn position_min_by_key<I, F, X>(iter: I, mut f: F) -> Option<usize>
82 where I: IntoIterator,
83 X: Ord,
84 F: FnMut(&I::Item) -> X
85{
86 iter.into_iter()
87 .enumerate()
88 .min_by_key(|x| f(&x.1))
89 .map(|x| x.0)
90}
91
92/// Creates a `Vector` from a iterator.
93///
94/// ```
95/// use fera_fun::vec;
96///
97/// assert_eq!(vec![1, 2, 3], vec(1..4));
98/// ```
99pub fn vec<I>(iter: I) -> Vec<I::Item>
100 where I: IntoIterator
101{
102 iter.into_iter().collect()
103}
104
105/// Creates a `HashSet` from a iterator.
106///
107/// ```
108/// use fera_fun::set;
109///
110/// assert_eq!(set(&[4, 3, 8, 3]), set(&[3, 4, 8]))
111/// ```
112pub fn set<I>(iter: I) -> HashSet<I::Item>
113 where I: IntoIterator,
114 I::Item: Hash + Eq
115{
116 iter.into_iter().collect()
117}