]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/monad.rs
test: Make manual changes to deal with the fallout from removal of
[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 // ignore-fast
12
13 use std::vec_ng::Vec;
14
15 trait vec_monad<A> {
16     fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> ;
17 }
18
19 impl<A> vec_monad<A> for Vec<A> {
20     fn bind<B>(&self, f: |&A| -> Vec<B> ) -> Vec<B> {
21         let mut r = Vec::new();
22         for elt in self.iter() {
23             r.push_all_move(f(elt));
24         }
25         r
26     }
27 }
28
29 trait option_monad<A> {
30     fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B>;
31 }
32
33 impl<A> option_monad<A> for Option<A> {
34     fn bind<B>(&self, f: |&A| -> Option<B>) -> Option<B> {
35         match *self {
36             Some(ref a) => { f(a) }
37             None => { None }
38         }
39     }
40 }
41
42 fn transform(x: Option<int>) -> Option<~str> {
43     x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str()) )
44 }
45
46 pub fn main() {
47     assert_eq!(transform(Some(10)), Some(~"11"));
48     assert_eq!(transform(None), None);
49     assert!((vec!(~"hi"))
50         .bind(|x| vec!(x.clone(), *x + "!") )
51         .bind(|x| vec!(x.clone(), *x + "?") ) ==
52         vec!(~"hi", ~"hi?", ~"hi!", ~"hi!?"));
53 }