]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/monad.rs
Imported Upstream version 1.2.0+dfsg1
[rustc.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
14 trait vec_monad<A> {
15 fn bind<B, F>(&self, f: F ) -> Vec<B> where F: FnMut(&A) -> Vec<B> ;
16 }
17
18 impl<A> vec_monad<A> for Vec<A> {
19 fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> {
20 let mut r = Vec::new();
21 for elt in self {
22 r.extend(f(elt));
23 }
24 r
25 }
26 }
27
28 trait option_monad<A> {
29 fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B>;
30 }
31
32 impl<A> option_monad<A> for Option<A> {
33 fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B> {
34 match *self {
35 Some(ref a) => { f(a) }
36 None => { None }
37 }
38 }
39 }
40
41 fn transform(x: Option<isize>) -> Option<String> {
42 x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) )
43 }
44
45 pub fn main() {
46 assert_eq!(transform(Some(10)), Some("11".to_string()));
47 assert_eq!(transform(None), None);
48 assert_eq!((vec!("hi".to_string()))
49 .bind(|x| vec!(x.clone(), format!("{}!", x)) )
50 .bind(|x| vec!(x.clone(), format!("{}?", x)) ),
51 ["hi".to_string(),
52 "hi?".to_string(),
53 "hi!".to_string(),
54 "hi!?".to_string()]);
55 }