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