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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright (c) 2014 Guillaume Pinot <texitoi(a)texitoi.eu>
//
// This work is free. You can redistribute it and/or modify it under
// the terms of the Do What The Fuck You Want To Public License,
// Version 2, as published by Sam Hocevar. See the COPYING file for
// more details.

#![deny(missing_docs)]
#![deny(warnings)]

//! Monadic do notation

/// Monadic do notation using duck typing
///
/// Syntax:
/// `(instr)* ; ret expr`
///
/// instr can be:
///
/// * `pattern =<< expression`: bind expression to pattern. a `bind`
///   function must be in scope.
///
/// * `let pattern = expression`: assign expression to pattern, as
///   normal rust let.
///
/// * `ign expression`: equivalent to `_ =<< expression`
///
/// * `when expression`: filter on the monad. `ret` and `mzero`
///   functions must be in scope.
///
/// # Example
///
/// ```
/// #[macro_use] extern crate mdo;
/// fn main() {
///     use mdo::iter::{bind, ret, mzero};
///     let l = mdo! {
///         x =<< 0i32..5; // assign x to [0, 5[
///         ign 0..2; // duplicate each value
///         when x % 2 == 0; // filter on even values
///         let y = x + 5; // create y
///         ret ret(y + 5) // return y + 5
///     }.collect::<Vec<_>>();
///     assert_eq!(l, vec![10, 10, 12, 12, 14, 14]);
/// }
/// ```
#[macro_export]
macro_rules! mdo {
    (
        let $p: pat = $e: expr ; $( $t: tt )*
    ) => (
        { let $p = $e ; mdo! { $( $t )* } }
    );

    (
        let $p: ident : $ty: ty = $e: expr ; $( $t: tt )*
    ) => (
        { let $p: $ty = $e ; mdo! { $( $t )* } }
    );

    (
        $p: pat =<< $e: expr ; $( $t: tt )*
    ) => (
        bind($e, move |$p| mdo! { $( $t )* } )
    );

    (
        $p: ident : $ty: ty =<< $e: expr ; $( $t: tt )*
    ) => (
        bind($e, move |$p : $ty| mdo! { $( $t )* } )
    );

    (
        ign $e: expr ; $( $t: tt )*
    ) => (
        bind($e, move |_| mdo! { $( $t )* })
    );

    (
        when $e: expr ; $( $t: tt )*
    ) => (
        bind(if $e { ret(()) } else { mzero() }, move |_| mdo! { $( $t )* })
    );

    (
        ret $f: expr
    ) => (
        $f
    )
}

pub mod option {
    //! Monadic functions for Option<T>

    /// bind for Option<T>, equivalent to `m.and_then(f)`
    pub fn bind<T, U, F: FnMut(T) -> Option<U>>(m: Option<T>, mut f: F) -> Option<U> {
        match m {
            Some(a) => f(a),
            None => None
        }
    }

    /// return for Option<T>, equivalent to `Some(x)`
    pub fn ret<T>(x: T) -> Option<T> {
        Some(x)
    }

    /// mzero for Option<T>, equivalent to `None`
    pub fn mzero<T>() -> Option<T> {
        None
    }
}

pub mod result {
    //! Monadic functions for Result<T, E>

    /// bind for Result<T, E>, equivalent to `m.and_then(f)`
    pub fn bind<T, E, U, F: FnMut(T) -> Result<U, E>>(m: Result<T, E>, mut f: F) -> Result<U, E> {
        match m {
            Ok(a) => f(a),
            Err(err) => Err(err)
        }
    }

    /// return for Result<T, E>, equivalent to `Ok(x)`
    pub fn ret<T, E>(x: T) -> Result<T, E> {
        Ok(x)
    }
}

pub mod iter {
    //! Monadic functions for Iterator<T>

    use std::option;
    use std::iter::FlatMap;

    /// bind for Iterator<T, E>, equivalent to `m.flat_map(f)`
    pub fn bind<I, U, F>(m: I, f: F) -> FlatMap<I, U, F>
    where I: Iterator, U: Iterator, F: FnMut(<I as Iterator>::Item) -> U {
        m.flat_map(f)
    }

    /// return for Iterator<T>, an iterator with one value.
    pub fn ret<T>(x: T) -> option::IntoIter<T> {
        Some(x).into_iter()
    }

    /// mzero for Iterator<T>, an empty iterator.
    pub fn mzero<T>() -> option::IntoIter<T> {
        None.into_iter()
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn option_bind() {
        use super::option::{bind, ret, mzero};
        let x = ret(5);
        assert_eq!(x, Some(5));
        let x = bind(ret(5), |x| ret(x + 1));
        assert_eq!(x, Some(6));
        let x = bind(ret(5), |x| bind(ret(x + 5), |x| ret(x * 2)));
        assert_eq!(x, Some(20));
        let x = bind(ret(5i32), |x| bind(if x == 0 { ret(()) } else { mzero() },
                                         |_| ret(x * 2)));
        assert_eq!(x, None);
    }

    #[test]
    fn option_mdo() {
        use super::option::{bind, ret, mzero};
        let x = mdo! {
            ret ret(5)
        };
        assert_eq!(x, Some(5));
        let x = mdo! {
            x =<< ret(5);
            ret ret(x + 1)
        };
        assert_eq!(x, Some(6));
        let x = mdo! {
            x =<< ret(5);
            x =<< ret(x + 5);
            ret ret(x * 2)
        };
        assert_eq!(x, Some(20));
        let x = mdo! {
            x =<< ret(5i32);
            when x == 0;
            ret ret(x * 2)
        };
        assert_eq!(x, None);
    }

    #[test]
    fn let_type() {
        let _: i32 = mdo! {
            let i: i32 = 0;
            ret i
        };
    }

    #[test]
    fn iter_bind() {
        use super::iter::{bind, ret, mzero};
        let l = bind(0..3, move |x| x..3);
        assert_eq!(l.collect::<Vec<_>>(), vec![0, 1, 2, 1, 2, 2]);
        let l = bind(0i32..3, move |x|
                     bind(0..3, move |y| ret(x + y)));
        assert_eq!(l.collect::<Vec<_>>(), vec![0, 1, 2, 1, 2, 3, 2, 3, 4]);
        let l = bind(1i32..11, move |z|
                     bind(1..z + 1, move |y|
                          bind(1..y + 1, move |x|
                               bind(if x * x + y * y == z * z { ret(()) }
                                    else { mzero() },
                                    move |_|
                                    ret((x, y, z))))));
        assert_eq!(l.collect::<Vec<_>>(), vec![(3, 4, 5), (6, 8, 10)]);
    }

    #[test]
    fn iter_mdo() {
        use super::iter::{bind, ret, mzero};
        let l = mdo! {
            x =<< 0..3;
            ret x..3
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![0, 1, 2, 1, 2, 2]);
        let l = mdo! {
            x =<< 0i32..3;
            y =<< 0..3;
            ret ret(x + y)
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![0, 1, 2, 1, 2, 3, 2, 3, 4]);
        let l = mdo! {
            z =<< 1i32..11;
            y =<< 1..z;
            x =<< 1..y + 1;
            let test = x * x + y * y == z * z;
            when test;
            let res = (x, y, z);
            ret ret(res)
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![(3, 4, 5), (6, 8, 10)]);
    }

    #[test]
    fn iter_ignore() {
        use super::iter::{bind, ret};
        let l = mdo! {
            x =<< 0i32..5;
            ign 0..2;
            ret ret(x)
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4]);
    }

    #[test]
    fn ret_trick() {
        use super::iter::bind;
        let l = mdo! {
            ret =<< 0..5;
            ret 0..ret
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![0, 0, 1, 0, 1, 2, 0, 1, 2, 3]);
    }

    #[test]
    fn when_trick() {
        use super::iter::{bind, ret, mzero};
        let l = mdo! {
            when =<< 0i32..5;
            when when != 3;
            ret ret(when)
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![0, 1, 2, 4]);
    }

    #[test]
    fn ign_trick() {
        use super::iter::{bind, ret};
        let l = mdo! {
            ign =<< 0i32..5;
            ign 0..0;
            ret ret(ign)
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![]);
    }

    #[test]
    fn mdo_doc_example() {
        use super::iter::{bind, ret, mzero};
        let l = mdo! {
            x: i32 =<< 0..5; // assign x to [0, 5[
            ign 0..2; // duplicate each value
            when x % 2 == 0; // filter on even values
            let y = x + 5; // create y
            ret ret(y + 5) // return y + 5
        }.collect::<Vec<_>>();
        assert_eq!(l, vec![10, 10, 12, 12, 14, 14]);
    }
}