├── .gitignore ├── .gitlab-ci.yml ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md ├── misc └── index.html ├── src └── lib.rs └── tests ├── lib.rs ├── list.rs ├── option.rs └── result.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | image: scorpil/rust:stable 2 | 3 | test: 4 | script: 5 | - cargo test 6 | 7 | pages: 8 | stage: deploy 9 | script: 10 | - cargo doc 11 | - mkdir public 12 | - cp -r target/doc/* public 13 | - cp misc/index.html public/ 14 | artifacts: 15 | paths: 16 | - public 17 | only: 18 | - master 19 | 20 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: rust 4 | rust: 5 | - nightly 6 | - beta 7 | - stable 8 | # - 1.0.0 9 | # - 1.1.0 10 | # - 1.2.0 11 | # - 1.3.0 12 | # - 1.4.0 13 | 14 | os: 15 | - linux 16 | - osx 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hado" 3 | version = "0.1.1" 4 | authors = ["Lucas David Traverso "] 5 | # A short blurb about the package. This is not rendered in any format when 6 | # uploaded to crates.io (aka this is not markdown). 7 | description = "Monadic do notation using a macro" 8 | 9 | # These URLs point to more information about the repository. 10 | # documentation = "" 11 | homepage = "https://github.com/ludat/hado-rs" 12 | repository = "https://github.com/ludat/hado-rs" 13 | 14 | # This points to a file in the repository (relative to this `Cargo.toml`). The 15 | # contents of this file are stored and indexed in the registry. 16 | readme = "README.md" 17 | 18 | # This is a small list of keywords used to categorize and search for this 19 | # package. 20 | keywords = ["macro", "monad", "do"] 21 | 22 | # This is a string description of the license for this package. Currently 23 | # crates.io will validate the license provided against a whitelist of known 24 | # license identifiers from http://spdx.org/licenses/. Multiple licenses can be 25 | # separated with a `/`. 26 | license = "Apache-2.0" 27 | 28 | [dependencies] 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hado 2 | 3 | Monadic haskell-like expressions brought to rust via the `hado!` macro 4 | 5 | ## What? 6 | 7 | A little macro for writing haskell-like do expressions without too much ceremony 8 | 9 | ## Why? 10 | 11 | Rust is a very explicit language when it comes to errors (via Option and Result 12 | types) but it can get cumbersome to handle all of them, so this library brings 13 | the composable monad pattern from haskell like languages. 14 | 15 | Let's show an example: We will try to do simple math and compose possible 16 | failures. 17 | 18 | First we define our return type, this type will represent the failure or success 19 | of the functions. 20 | 21 | ```rust 22 | type MathResult = Option; 23 | ``` 24 | 25 | - Division: if the divisor is 0 we fail 26 | 27 | ```rust 28 | fn div(x: f64, y: f64) -> MathResult { 29 | if y == 0.0 { 30 | None 31 | } else { 32 | Some(x / y) 33 | } 34 | } 35 | ``` 36 | 37 | - Square root: if we get a negative number, we fail 38 | 39 | ```rust 40 | fn sqrt(x: f64) -> MathResult { 41 | if x < 0.0 { 42 | None 43 | } else { 44 | Some(x.sqrt()) 45 | } 46 | } 47 | ``` 48 | 49 | - Logarithm: again if we get a negative number, we fail 50 | 51 | ```rust 52 | fn ln(x: f64) -> MathResult { 53 | if x < 0.0 { 54 | None 55 | } else { 56 | Some(x.ln()) 57 | } 58 | } 59 | ``` 60 | 61 | Now we want to get two numbers, divide them, get the sqrt of the result and then 62 | get the logarithm of the last result 63 | 64 | ## The naive way 65 | 66 | ```rust 67 | fn op(x: f64, y: f64) -> MathResult { 68 | let ratio = div(x, y); 69 | if ratio == None { 70 | return None 71 | }; 72 | let ln = ln(ratio.unwrap()); 73 | if ln == None { 74 | return None 75 | }; 76 | return sqrt(ln.unwrap()) 77 | } 78 | ``` 79 | 80 | Even though this code works it's hard to scale, and it isn't idiomatic rust, it 81 | looks more like code you'd see in Java where `None` is `NULL`. 82 | 83 | ## The better way 84 | 85 | ```rust 86 | fn op(x: f64, y: f64) -> MathResult { 87 | match div(x, y) { 88 | None => None, 89 | Ok(ratio) => match ln(ratio) { 90 | None => None, 91 | Ok(ln) => sqrt(ln), 92 | }, 93 | } 94 | } 95 | ``` 96 | 97 | This example is more rustic but it still looks like too much noise, and still 98 | it's very hard to scale 99 | 100 | ## The FP way 101 | 102 | ```rust 103 | fn op(x: f64, y: f64) -> MathResult { 104 | div(x, y).and_then(|ratio| 105 | ln(ratio).and_then(|ln| 106 | sqrt(ln))) 107 | } 108 | ``` 109 | 110 | This way look almost like the special thing that we want to do but those 111 | `and_then` and closures seem unnecessary 112 | 113 | ## The hado macro way 114 | 115 | ```rust 116 | fn op(x: f64, y: f64) -> MathResult { 117 | hado! { 118 | ratio <- div(x, y); 119 | ln <- ln(ratio); 120 | sqrt(ln) 121 | } 122 | } 123 | ``` 124 | 125 | 126 | Here we have a very obvious way of declaring out intent without no sign of error 127 | handling of any kind, we needed to add a trait `Monad` to Option (which is 128 | already defined by default in this library) 129 | 130 | ## Error type agnostic 131 | 132 | Now some more fancy stuff, you may be thinking `but what about the try! macro, 133 | it would certainly make things better, right?` and my answer would be yes but 134 | the try macro _only_ works on the `Result` type so there is no way of changing 135 | the type of the error (or use it with our Option based functions). 136 | 137 | 138 | But now we need to know what was the error that made of computation fail. So we 139 | change the `MathResult` alias to be a Result of f64 or a custom type `MathError` 140 | 141 | ```rust 142 | #[derive(Debug)] 143 | pub enum MathError { 144 | DivisionByZero, 145 | NegativeLogarithm, 146 | NegativeSquareRoot, 147 | } 148 | 149 | type MathResult = Result; 150 | ``` 151 | 152 | So now we need to change each function because now all the `None` and `Some` 153 | constructors are a type error 154 | 155 | For example div turns into 156 | 157 | ```rust 158 | fn div(x: f64, y: f64) -> MathResult { 159 | if y == 0.0 { 160 | Err(MathError::DivisionByZero) 161 | } else { 162 | Ok(x / y) 163 | } 164 | } 165 | ``` 166 | 167 | note that the only changes are: 168 | 169 | - ~~None~~ `Err(MathError::DivisionByZero)` 170 | - ~~Some~~ `Ok (x / y)` 171 | 172 | and now we check out the op function for each implementation: 173 | 174 | * *Naive way*: Change all the constructors, the failure checker, luckily rust's 175 | type inference saves us from changing too many type declarations. 176 | * *Better way*: Slightly better, same constructors, but failure checkers are 177 | replaced by match statements but still very verbose. 178 | * *FP way*: a lot better, the only worry we have is that the new error type has 179 | some sort of ~and_then~ and everything else should work. 180 | * *hado way*: Similar to the last, but now there is nothing to change, the 181 | computation has no concern over the failure framework. 182 | 183 | # How can I use it? 184 | 185 | The macro can do some basic stuff based on a trait defined inside the crate 186 | *Monad* which has implementations for Option and Result by default 187 | 188 | Let's take some examples from the rust book and rust by example and translate 189 | them into hado format. 190 | 191 | ## [Example from Result type reference](https://doc.rust-lang.org/std/result/#the-try-macro) 192 | 193 | Here is the original try based error handling with early returns 194 | 195 | ```rust 196 | fn write_info(info: &str) -> io::Result<()> { 197 | let mut file = try!(File::create("my_best_friends.txt")); 198 | println!("file created"); 199 | try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes())); 200 | Ok(()) 201 | } 202 | ``` 203 | 204 | And here is the hado based 205 | 206 | ```rust 207 | fn hado_write_info(string: &str) -> io::Result<()> { 208 | hado!{ 209 | mut file <- File::create("my_best_friends.txt"); 210 | println!("file created"); 211 | file.write_all(format!("string: {}\n", string).as_bytes()) 212 | } 213 | } 214 | ``` 215 | 216 | Note that the ign keyword is special, it means that the inner value is discarded 217 | but in the case of failure the whole expressions will short circuit into that 218 | error. Since there is no arrow (`<-`) the return of the `println` is completely 219 | discarded so you can have any non failing statements in there (including `let` 220 | and `use`) 221 | 222 | ## Multi parameter constructor 223 | 224 | let's say we have a Foo struct that has a new method 225 | 226 | ```rust 227 | fn new(a: i32, b: f64, s: String) -> Foo { 228 | Foo { 229 | a: i32, 230 | b: f64, 231 | s: String 232 | } 233 | } 234 | ``` 235 | 236 | Create a Option constructor from a normal constructor with minimal hassle 237 | 238 | ```rust 239 | fn opt_new(a: Option, b: Option, s: Option) -> Option { 240 | a <- a; 241 | b <- b; 242 | s <- s; 243 | ret new(a, b, s) 244 | } 245 | ``` 246 | 247 | Note that only by changing the type signature you can change Option to any other 248 | monadic type. 249 | 250 | You can also do some custom validation without much boilerplate 251 | 252 | ```rust 253 | fn opt_new(a: i32, b: f64, s: String) -> Option { 254 | a <- validate_a(a); 255 | b <- validate_b(b); 256 | s <- validate_s(s); 257 | ret new(a, b, s) 258 | } 259 | ``` 260 | -------------------------------------------------------------------------------- /misc/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Hado documentation redirect 4 | 5 | 6 | 7 |
8 | This is the documentations for the hado library. It should redirect you to https://ludat.gitlab.io/hado-rs/hado/ 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! hado { 3 | (ret ( $ty:ty ) $expr:expr) => { 4 | $crate::Monad::< $ty >::ret($expr) 5 | }; 6 | (ret $expr:expr) => { 7 | $crate::Monad::ret($expr) 8 | }; 9 | (ign <- $expr:expr; $($rest:tt)*) => { 10 | $crate::Monad::bind($expr, |_| hado!($($rest)*)) 11 | }; 12 | (mut $ident:ident <- $expr:expr; $($rest:tt)*) => { 13 | $crate::Monad::bind($expr, |mut $ident| hado!($($rest)*)) 14 | }; 15 | ($ident:ident <- $expr:expr; $($rest:tt)*) => { 16 | $crate::Monad::bind($expr, |$ident| hado!($($rest)*)) 17 | }; 18 | ($stmt:stmt; $($rest:tt)*) => { 19 | { $stmt ; hado!($($rest)*) } 20 | }; 21 | ($expr:expr) => { 22 | $expr 23 | } 24 | } 25 | 26 | pub trait Monad { 27 | type Inner; 28 | fn bind(t: Self, f: F) -> O where F: FnMut(Self::Inner) -> O ; 29 | fn ret(Self::Inner) -> Self; 30 | } 31 | 32 | impl Monad> for Option { 33 | type Inner = T; 34 | fn bind(t: Option, mut f: F) -> Option 35 | where F: FnMut(T) -> Option { 36 | match t { 37 | Some(t) => f(t), 38 | None => None, 39 | } 40 | } 41 | fn ret(inner: T) -> Self { 42 | Some(inner) 43 | } 44 | } 45 | 46 | impl Monad> for Result { 47 | type Inner = T; 48 | fn bind(t: Result, mut f: F) -> Result 49 | where F: FnMut(T) -> Result { 50 | match t { 51 | Ok(t) => f(t), 52 | Err(e) => Err(e), 53 | } 54 | } 55 | fn ret(inner: T) -> Self { 56 | Ok(inner) 57 | } 58 | } 59 | 60 | impl Monad> for Vec { 61 | type Inner = T; 62 | fn bind(t: Self, mut f: F) -> Vec 63 | where F: FnMut(T) -> Vec { 64 | let mut acc: Vec = Vec::new(); 65 | for v in t { 66 | acc.append(&mut f(v)); 67 | } 68 | acc 69 | } 70 | fn ret(inner: T) -> Vec { 71 | vec![inner] 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /tests/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate hado; 3 | 4 | #[test] fn main() { 5 | assert_eq!( 6 | Some(3), 7 | hado! { 8 | x <- Some(1); 9 | y <- Some(2); 10 | Some(x + y) 11 | } 12 | ); 13 | assert_eq!( 14 | Some(3), 15 | hado! { 16 | x <- Some(1); 17 | println!("x: {:?}", x); 18 | y <- Some(2); 19 | Some(x + y) 20 | } 21 | ); 22 | assert_eq!( 23 | { let t: Vec = vec![0, 0, 1, 1, 2, 2]; t }, 24 | hado! { 25 | a <- vec![0, 1, 2]; 26 | println!("a: {:?}", a); 27 | b <- vec![a, a]; 28 | ret(Vec) b 29 | } 30 | ); 31 | assert_eq!( 32 | hado! { 33 | a <- vec![0, 1, 2]; 34 | b <- vec![a, a]; 35 | ret(Vec) b 36 | }, 37 | hado! { 38 | a <- vec![0, 1, 2]; 39 | vec![a, a] 40 | } 41 | ); 42 | assert_eq!( 43 | hado! { 44 | ign <- vec![0, 1, 2]; 45 | let b = 7; 46 | ret(Vec) b 47 | }, 48 | hado! { 49 | ign <- vec![0, 1, 2]; 50 | vec![7] 51 | } 52 | ); 53 | } 54 | 55 | #[test] fn file() { 56 | use std::fs::File; 57 | use std::io::prelude::*; 58 | use std::io; 59 | 60 | #[derive(Clone, PartialEq)] 61 | struct Info { 62 | name: String, 63 | age: i32, 64 | rating: i32, 65 | } 66 | 67 | 68 | fn monadic_write_info(info: &Info) -> io::Result<()> { 69 | hado!{ 70 | mut file <- File::create("my_best_friends.txt"); 71 | ign <- file.write_all(format!("name: {}\n", info.name).as_bytes()); 72 | ign <- file.write_all(format!("age: {}\n", info.age).as_bytes()); 73 | file.write_all(format!("rating: {}\n", info.rating).as_bytes()) 74 | } 75 | } 76 | 77 | println!("result: {:?}", 78 | monadic_write_info(&Info { 79 | name: "Lucas".to_string(), 80 | age: 20, 81 | rating: 15, 82 | }) 83 | ) 84 | } 85 | 86 | #[test] fn division() { 87 | // Mathematical "errors" we want to catch 88 | #[derive(Debug, PartialEq)] 89 | pub enum MathError { 90 | DivisionByZero, 91 | NegativeLogarithm, 92 | NegativeSquareRoot, 93 | } 94 | 95 | type MathResult = Result; 96 | // type MathResult = Option; 97 | 98 | fn div(x: f64, y: f64) -> MathResult { 99 | if y == 0.0 { 100 | Err(MathError::DivisionByZero) 101 | } else { 102 | Ok(x / y) 103 | } 104 | } 105 | fn sqrt(x: f64) -> MathResult { 106 | if x < 0.0 { 107 | Err(MathError::NegativeSquareRoot) 108 | } else { 109 | Ok(x.sqrt()) 110 | } 111 | } 112 | fn ln(x: f64) -> MathResult { 113 | if x < 0.0 { 114 | Err(MathError::NegativeLogarithm) 115 | } else { 116 | Ok(x.ln()) 117 | } 118 | } 119 | fn op(x: f64, y: f64) -> MathResult { 120 | hado! { 121 | ratio <- div(x, y); 122 | println!("{:?}", ratio); 123 | ln <- ln(ratio); 124 | println!("{:?}", ln); 125 | sqrt(ln) 126 | } 127 | } 128 | 129 | assert_eq!( 130 | op(1.0, 10.0), 131 | Err(MathError::NegativeSquareRoot) 132 | ); 133 | } 134 | -------------------------------------------------------------------------------- /tests/list.rs: -------------------------------------------------------------------------------- 1 | extern crate hado; 2 | 3 | use hado::Monad; 4 | 5 | #[test] #[ignore] fn empty_list_is_empty_list() { 6 | assert_eq!( 7 | { let t: Vec = vec![]; t }, 8 | Monad::>::bind(Vec::new(), |_: u32| vec![0, 0]) 9 | ); 10 | } 11 | #[test] #[ignore] fn two_lists_multiply() { 12 | assert_eq!( 13 | { let t: Vec = vec![0, 0, 0, 0, 0, 0]; t }, 14 | Monad::>::bind(vec![0, 0, 0], |_: u32| vec![0, 0]) 15 | ); 16 | } 17 | #[test] #[ignore] fn duplicate_list() { 18 | assert_eq!( 19 | { let t: Vec = vec![0, 0, 1, 1, 2, 2]; t }, 20 | Monad::>::bind(vec![0, 1, 2], |x: u32| vec![x, x]) 21 | ); 22 | } 23 | -------------------------------------------------------------------------------- /tests/option.rs: -------------------------------------------------------------------------------- 1 | extern crate hado; 2 | 3 | use hado::Monad; 4 | 5 | #[test] fn simple_map() { 6 | assert_eq!( 7 | Some(0), 8 | Monad::bind(Some(1), |x| Some(x*0)) 9 | ); 10 | } 11 | #[test] fn two_level_deep() { 12 | assert_eq!( 13 | Some(3), 14 | Monad::bind(Some(1), |x| Monad::bind(Some(2), |y| Some(x + y))) 15 | ); 16 | } 17 | #[test] fn if_none_ignore_function() { 18 | assert_eq!( 19 | None, 20 | Monad::bind(None, |x: u32| Some(x*0)) 21 | ); 22 | } 23 | -------------------------------------------------------------------------------- /tests/result.rs: -------------------------------------------------------------------------------- 1 | extern crate hado; 2 | 3 | use hado::Monad; 4 | 5 | #[test] fn simple_map() { 6 | assert_eq!( 7 | Ok(0), 8 | Monad::>::bind(Ok(1), |x: u32| Ok(x*0)) 9 | ); 10 | } 11 | #[test] fn fail_fast() { 12 | assert_eq!( 13 | Err("failed"), 14 | Monad::bind(Err("failed"), |x: u32| Ok(x*0)) 15 | ); 16 | } 17 | --------------------------------------------------------------------------------