News for hackers. Stuff that matters.
Re:Functors, applicatives, and monads in pictures by steveklabnik on Sunday May 19, 2013 @12:01PM (#5733231)
The big difference is that it's statically computed.

Rust also has a Maybe type as well. You use it like this:

  use core::io::{Reader,ReaderUtil};
  use core::io::println;

  fn main() {
      let in = io::stdin().read_line();
      println("INPUT:");
      println(int::str(int::from_str(in)));
  }
This code will produce an error, because `int::from_str` can fail. Imagine trying to convert a number from the string "foobar".

  $ make
  rustc option.rs
  option.rs.rs:125:23: 125:41 error: mismatched types: expected `int` but found 
  `core::option::Option<int>` (expected int but found enum core::option::Option)
  option.rs:125   io::println(int::str(int::from_str(in)));
                                         ^~~~~~~~~~~~~~~~~~
  error: aborting due to previous error
  make: *** [build] Error 101
What Rust is saying here is that we don't have the right types: `int::str` takes an int, but `int::from_str` returns an `Option<int>`.

We can make the compiler satisfied by pattern matching over the return value:

  use core::io::{Reader,ReaderUtil};
  use core::io::println;

  fn main() {
      let in = io::stdin().read_line();

      match int::from_str(in) {
          Some(number_string) => println(int::to_str(number_string)),
          None                => println("Hey, put in a number.")
      }
  }
Now, we explicitly handle both cases (Some(x) being a success, and None being the failure), and the compiler is happy.

This is where the advantages of Maybe come into play. In dynamic languages, you don't get the advantage of always making sure you handle the degenerate case.

Now, what the Maybe _monad_ does is allow you to chain multiple things that work with Maybe together. I don't have a Rust example of this handy. Like "Do this, do that, do the other thing, and then let's see if that failed anywhere along the way."

There are no comments on this comment yet.