1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// This trait creates a `flat_map` method for `Option` (equivalent to
// `Option::and_then`) so that it can be used in the `map_for` macro.
pub trait FlatMap<Item> {
   type Item;
   fn flat_map<U, F> (self, f: F) -> Option<U>
      where F: FnOnce (Self::Item) -> Option<U>;
}
impl<Item> FlatMap<Item> for Option<Item> {
   type Item = Item;
   fn flat_map<U, F> (self, f: F) -> Option<U>
      where F: FnOnce (Self::Item) -> Option<U>
   { self.and_then (f) }
}

// This trait creates a `filter` method for `Option` so that it can be
// filtered on when used in the `map_for` macro.
pub trait Filter<Item> {
   type Item;
   fn filter<P> (self, predicate: P) -> Option<Item>
      where P: FnOnce (&Self::Item) -> bool;
}
impl<Item> Filter<Item> for Option<Item> {
   type Item = Item;
   fn filter<P> (self, predicate: P) -> Option<Item>
      where P: FnOnce (&Self::Item) -> bool
   { self.and_then (|item| if predicate (&item) { Some (item) } else { None }) }
}

// Scala-like for comprehension similar to those described in
// https://stackoverflow.com/questions/3754089/scala-for-comprehension#3754568
// The main difference is that since rust does not have partial
// functions, we do not support general patterns in the left-hand
// sides, but only single identifiers and list of identifiers (that
// will match a tuple).
#[macro_export]
macro_rules! map_for {
   // Process tuple patterns. Note that this must come first due to
   // rust issue #27832.
   (($($n:ident),+) <- $e:expr; => $e0:expr) => (
      $e.map (move |params| {
         #[allow(unused_variables)] let ($($n),+) = params;
         $e0 }));
   (($($n:ident),+) <- $e:expr; if $g:expr; $($tail:tt)+) => (
      map_for! {
         ($($n),+) <- $e.filter (|params| {
            #[allow(unused_variables)] let ($($n),+) = *params;
            $g });
         $($tail)+ });
   (($($n:ident),+) <- $e:expr; ($($n0:ident),+) <- $e0:expr; $($tail:tt)+) => (
      $e.flat_map (move |params| {
         #[allow(unused_variables)] let ($($n),+) = params;
         map_for!{ ($($n0),+) <- $e0; $($tail)+ } }));
   (($($n:ident),+) <- $e:expr; $n0:ident <- $e0:expr; $($tail:tt)+) => (
      $e.flat_map (move |params| {
         #[allow(unused_variables)] let ($($n),+) = params;
         map_for!{ $n0 <- $e0; $($tail)+ } }));
   (($($n:ident),+) <- $e:expr; $n0:ident = $e0:expr; $($tail:tt)+) => (
      map_for!{
         ($($n),+, $n0) <- map_for!{$($n),+ <- $e; => {
            let $n0 = $e0; ($($n),+, $n0) } };
         $($tail)+ });

   // Process single-identifier patterns.
   ($n:ident <- $e:expr; => $e0:expr) => ($e.map (move |$n| { $e0 }));
   ($n:ident <- $e:expr; if $g:expr; $($tail:tt)+) => (
      map_for! { $n <- $e.filter (|$n| { $g }); $($tail)+ });
   ($n:ident <- $e:expr; $n0:ident <- $e0:expr; $($tail:tt)+) => (
      $e.flat_map (move |$n| { map_for!{ $n0 <- $e0; $($tail)+ } }));
   ($n:ident <- $e:expr; $n0:ident = $e0:expr; $($tail:tt)+) => (
      map_for!{
         ($n, $n0) <- map_for!{$n <- $e; => {
            let $n0 = $e0; ($n, $n0) } };
         $($tail)+ });
}

#[cfg(test)]
mod tests {
   use super::*;

   #[test]
   fn tuple() {
      let c = map_for!{
         (a, b) <- Some ((1, 2));
         => a + b };
      assert_eq!(c, Some (3));
   }

   #[test]
   fn option() {
      let c = map_for!{
         a <- Some (1);
         b <- Some (2);
         => { a + b } };
      assert_eq!(c, Some (3));
   }

   #[test]
   fn range() {
      let l = map_for!{
         x <- 0..4;
         y <- 0..x;
         => y
         // x == 0 -> empty
         // x == 1 -> 0
         // x == 2 -> 0, 1
         // x == 3 -> 0, 1, 2
      }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 0, 0, 1, 0, 1, 2 ]);
   }

   #[test]
   fn capture() {
      let count = 3;
      let offset = 2;
      let l = map_for!{
         x <- 0..4;
         y <- 0..count;
         => x + y + offset
      }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 2, 3, 4,
                          3, 4, 5,
                          4, 5, 6,
                          5, 6, 7 ]);
   }

   #[test]
   fn regular_binding() {
      let l = map_for!{
         x <- 0..4;
         y = 2*x;
         z <- 0..1;
         => y+z
      }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 0, 2, 4, 6 ]);
   }

   #[test]
   fn filtering() {
      let l = map_for!{
         x <- 0..10;
         if (x%2) == 0;
         => x }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 0, 2, 4, 6, 8 ]);

      let l = map_for!{
         x <- 0..10;
         y = x/2;
         if (y%2) == 0;
         => y }.collect::<Vec<_>>();
      assert_eq!(l, vec![0, 0, 2, 2, 4, 4]);
   }

   #[test]
   fn filtering_options() {
      let c = map_for!{
         a <- Some (1);
         b <- Some (2);
         if (b%2) == 0;
         => { a + b } };
      assert_eq!(c, Some (3));
      let c = map_for!{
         a <- Some (1);
         if (a%2) == 0;
         b <- Some (2);
         => { a + b } };
      assert_eq!(c, None);
   }
}