]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/monad.rs
auto merge of #14415 : Sawyer47/rust/ascii-fixme, r=huonw
[rust.git] / src / test / run-pass / monad.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12
13 trait vec_monad<A> {
14     fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> ;
15 }
16
17 impl<A> vec_monad<A> for Vec<A> {
18     fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> {
19         let mut r = Vec::new();
20         for elt in self.iter() {
21             r.push_all_move(f(elt));
22         }
23         r
24     }
25 }
26
27 trait option_monad<A> {
28     fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B>;
29 }
30
31 impl<A> option_monad<A> for Option<A> {
32     fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B> {
33         match *self {
34             Some(ref a) => { f(a) }
35             None => { None }
36         }
37     }
38 }
39
40 fn transform(x: Option<int>) -> Option<String> {
41     x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str().to_strbuf()) )
42 }
43
44 pub fn main() {
45     assert_eq!(transform(Some(10)), Some("11".to_strbuf()));
46     assert_eq!(transform(None), None);
47     assert!((vec!("hi".to_strbuf()))
48         .bind(|x| vec!(x.clone(), format_strbuf!("{}!", x)) )
49         .bind(|x| vec!(x.clone(), format_strbuf!("{}?", x)) ) ==
50         vec!("hi".to_strbuf(),
51              "hi?".to_strbuf(),
52              "hi!".to_strbuf(),
53              "hi!?".to_strbuf()));
54 }