]> git.lizzy.rs Git - rust.git/blob - tests/ui/traits/monad.rs
Merge commit '598f0909568a51de8a2d1148f55a644fd8dffad0' into sync_cg_clif-2023-01-24
[rust.git] / tests / ui / traits / monad.rs
1 // run-pass
2
3 #![allow(non_camel_case_types)]
4
5
6
7 trait vec_monad<A> {
8     fn bind<B, F>(&self, f: F ) -> Vec<B> where F: FnMut(&A) -> Vec<B> ;
9 }
10
11 impl<A> vec_monad<A> for Vec<A> {
12     fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> {
13         let mut r = Vec::new();
14         for elt in self {
15             r.extend(f(elt));
16         }
17         r
18     }
19 }
20
21 trait option_monad<A> {
22     fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B>;
23 }
24
25 impl<A> option_monad<A> for Option<A> {
26     fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B> {
27         match *self {
28             Some(ref a) => { f(a) }
29             None => { None }
30         }
31     }
32 }
33
34 fn transform(x: Option<isize>) -> Option<String> {
35     x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) )
36 }
37
38 pub fn main() {
39     assert_eq!(transform(Some(10)), Some("11".to_string()));
40     assert_eq!(transform(None), None);
41     assert_eq!((vec!["hi".to_string()])
42         .bind(|x| vec![x.clone(), format!("{}!", x)] )
43         .bind(|x| vec![x.clone(), format!("{}?", x)] ),
44         ["hi".to_string(),
45          "hi?".to_string(),
46          "hi!".to_string(),
47          "hi!?".to_string()]);
48 }