Maybe is usually used as an example since it's the simplest non-trivial monad (and therefore also an applicative functor).
The point of eg. fmap etc. is that you can have regular Int -> Bool functions, and apply them to data with more structure than simple values. a Maybe String is not a String, but you can still transform one to uppercase by doing fmap (map toUpper) mstring. The fun part is that that exact same thing works on a list of strings, an IO String (fmap (map toUpper) getLine), a Tree of Strings, etc... It's fully generic over anything that can implement Functor; the exact behaviour is defined by the particular instance.
Applicative is just an extension to the idea, where the function applied itself can have this extra structure, and when combined with an infix fmap you get to do
(+) <$> Just 2 <*> Nothing <*> Just 5 -- Nothing
(++) <$> getLine <*> getLine -- IO action that reads two lines and concats them
To see why this works has to do with currying. Just stare at the types of fmap and <* > long enough and you should see it eventually.a Monad is yet more powerful because it allows a previous computation to affect what follows in an arbitrary manner (Applicative doesn't), allowing things like state, asynchronous execution, continuations, and countless other things. It's such an useful abstraction that Haskell provides the do syntax for using it.
Edit: In languages like Java where all types are nullable, if you uppercase a String, but that String is null, your program breaks, even though the type system claims that you have a String when in reality all types are Maybes, and you are forced to always check for nulls manually or just rely on users to not give you nulls, even though it would be trivial for the compiler to check something like that statically if the language were expressive enough to allow it.
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."
Asynchronous execution is one particular case that I like as an example: You can implement promises (which represent async computations) in Haskell and such a Promise type will also be able to implement the monad type class. Because they are monads, you can use do notation:
-- Let's assume we want to fetch two large datasets asynchronously over the network and filter them
asyncSanitize :: Promise [String] -> Promise [String] -> Promise [String]
asyncSanitize p1 p2 = do
x <- p1
y <- p2
return (sanitize (x ++ y)) -- no callbacks!
which looks like the same code you would use for filtering two Maybe values using do notation. In fact, it is the same code, and if you leave out the type signature, then "asyncSanitize" will work for any monadic value: you could easily test your function using eg. Identity [String] (pure values), IO String (synchronous fetching), or decide to switch to some Database monad instead that fetches the values on demand from the Database. The code will not need to change at all.Think of Maybe as a container. It either "contains" a value, or it doesn't. The container itself is not usable except for passing around; it's the contained value that is important. Even if we know that the container is supposed to contain a number, we can't use the container to perform computations; every time we need the number, we need to open the container, peek inside, and decide what to do whether it's contains something or nothing.
In Haskell terms, this "peeking inside" is typically done with pattern matching, which is core to the type system. For example, this is a function that checks if a Maybe value has anything, and returns true or false:
hasValue x =
case x of
Just _ -> True
Nothing -> False
The line "Just _" is a kind of wildcard expression, meaning: "Check if x matches the pattern Just [something]".At the opposite end, we can have functions that produce Maybes (naive and simplified example, not working code):
fetchPage url =
do response <- performHttpRequest "GET" url
case (getStatusCode response)
200 -> return (Just (getBody response))
404 -> return Nothing
Notice how "Just" looks like a function call. That's because it is. It's a function that "constructs" a value of, in this case, type "Maybe String". The "Nothing" returned is also a value of type "Maybe String". Thanks to Haskell's type inference, this is known at compile time.In languages such as Java or Ruby we can build classes that are containers that act in a similar way. But those languages are limited in that "peek inside the container" logic needs to happen at runtime. In Haskell, the container's possible values are enforced entirely by the type system at compile time.
To really appreciate this, you really have to be familiar with statically typed languages such as C++ or Java. In such languages, you have "nil" or "null" or "NULL" values to represent "nothing". Any time you have a pointer, you have to explicitly check if the pointer is valid; if you try to use it, and it happens to be null, the program will blow up at runtime, but not at compile time.
In Haskell, there is no generic null value. The value "Nothing" on its own belongs to a specific type, such as "Maybe String", and won't work with another such as "Maybe Integer". Thus when we want to use "fetchPage", we are forced into a situation where must make a choice based on whether there is a value or not (again, naive example):
crawlPageRecursively url =
do contents <- fetchPage url
case contents of
Just s -> map crawlPageRecursively (map (\body -> getLinks body) s)
Nothing -> putStrLn ("Failed to fetch " ++ url)
Since Haskell doesn't have null pointers, and can never end up in a situation where you try to use a null where you expected a value, because its type system makes it impossible.This was my attempt at "explain it like I'm five" Haskell as carefully as I could. The real world is somewhat more complex, but not awfully so. As you say, too often haskellers will get into "formal academic theory", even when, in my opinion, it's not necessary. Haskell becomes more elegant and beautiful if you study and know group theory, but most people don't, and it really just obscures the language for ordinary, mortal programmers who are trying to learn it.
As for monads, it's true that Maybe is a monad, but think of it as a convenience, in the sense that this lets it play well with the rest of the monad infrastructure. You can use, and even implement, Maybe without involving the monad aspect.
My best suggestion regarding monads is to just start using the language; as DanWaterworth points out, monads are pretty much inexplicable for beginners until one really needs to use them. Haskell actually lets you use some monads (like IO) without requiring any deep understanding of what they are. Case in point: The above examples actually use the IO monad, concealed by the "do" and the "<-" syntax. But because this syntactic sugar makes the language look like an imperative language, you can use this stuff without too much deep knowledge about just exactly how it works under the hood.
The audience level of this piece is confusing -- it looks like a friendly, cartoony introduction for a general audience, but it actually assumes you already know Haskell.
Basically, you and I are not the intended audience.
i wish people who are writing guides on these topics pick a non-simplified situation where using this method makes for an easier program (vs using the "traditional method"). The comparison and contrasting of a functional/monadic approach vs a procedural approach in a complex scenario might actually shed more light - at least, for some one who is familiar with the procedural approach.
http://book.realworldhaskell.org/read/programming-with-monad...
"Learn You A Haskell For Great Good" [1], while much less complete, is the best intro I have found so far. It's also free.
There are very few things in the world of CS/programming where I can't follow along and grok what's going on, especially when laid out in a tutorial form like this. The fact that I was totally lost when reading this is not a good sign when you're trying to get people to adopt your school of thought.
At the end of the day, you adopt a new way of thinking that is incredibly clarifying for all programming. One simple thing is that it allows you to "see" where state, re-entry, evaluation, IO, and failure are happening in a program---things that you are blind to when you're used to languages where the answer is "always".
This article isn't even meant to explain why you ought to learn Haskell. It's more like a signpost on your path to mastery, should you begin walking it.
That's probably because most of the tutorials you've followed have adopted an imperative style of programming. It is easy for you to follow along because it really isn't all that different from what you are accustomed to. Functional programming really is a different beast entirely. It's often said (though I remain skeptical) that it's actually easier to learn functional programming as a non-programmer than to un-learn your imperative programming tendencies.
>The fact that I was totally lost when reading this is not a good sign when you're trying to get people to adopt your school of thought.
I don't think that's a fair assessment. You could say the same thing about starting from functional programming and switching to imperative; some people actually do this! They find the idea of mutating a variable to be completely counter-intuitive!
The notion of mutation is implicit in the definition of "variable."
So you don't change it during one exercise, but you can and certainly will change it when you change the exercise to another one with the same principle.
For example, if you integrate x^2 dx from x=0 to 10, x changes continuously.
It's clear that x is not fixed to any particular value.
foo x = x * 2
Every time you call foo, x is bound to a new value (but only within the scope of foo). This is not the same as mutating some memory location associated with the name x.The series of additions can also be infinite, in which case it would be quite difficult to expand fully, but that doesn't prevent you from doing mathematics with it.
That's not analogous at all to mutation.
As someone who'd done reasonably well with both and had thought of them as heavily overlapping areas, I thought this was interesting, so I tried to poke at this a bit.
One of the concepts I got back from a talented classmate was basically a complaint about mutable variables -- that in an algebraic description of relationships for a given system what we call "variables" are less variable and more "unknowns" which represent fixed if unidentified quantities. Others similarly noted there was something absurd about writing out equations like "x = x + 2".
The trick is to stop reading that line (in your head) as "x is equal to x plus two", but instead "x is assigned the value of x plus two".
That's one potential takeaway, but when I turned over the complaint in my mind, this was arguably another way of complaining about mutability.
Also, given the timing, it's pretty likely that one of the languages they'd learned was Pascal: that was the language of the first few CS classes at my school in the 90s, it was also the language of any high school curriculum that led to the AP exam, and Borland's Pascal products were still pretty popular PC dev environments.
They could've also been unlucky and received their first exposure by choosing to do a numerical analysis class in Fortran or C, of course. :/
Source: all my classmates.
Haskell is difficult to explain because it has many terms, vocabulary, and syntax that are not familiar to people. It's ML-style syntax doesn't help.
Most tutorials targeting Haskell beginners implicitly assume the readers already know the Haskell syntax, terms, definition, etc, and go right ahead to explain the advance concepts like functor, applicative, or monad. It's like teaching them how to fly before they know how to walk, in the Haskell land. No wonder Haskell beginners are frustrated with any of the monad tutorial.
The thing is. Stop. Stop telling beginners what monad is. Just show them the basics in Haskell and get something useful going. Get them to write and use Haskell programs. When the need arise, they will look into what monad is. Programmers have used STL plenty without knowing the internals of C++ templates. Same thing can be done with monad.
> When the need arise, they will look into what monad is.
I couldn't have said it any better. This is the exact scenario that this post is aimed at.
The Haskell community has a longstanding tradition of using condescending language ("fmap is from the street, fmap is hip to contexts."), and deliberate childrens-book style metaphors and illustrations in tutorials.
The theory seem to be that if monads haven't been adopted by mainstream developers yet, it is just because the presentations haven't been dumbed-down and kiddie-friendly enough yet. (If only they from the onset had called "monads" for "warm fuzzy things" instead, surely developers would not be so scared of them!)
The strategy have not yet borne fruit, though.
There's no way this Java thing will catch on. Why would anyone choose to deal with it?
print "Hello World"
And in the case of Java, it is well known that Java is not intended or used for writing one-lines, so it is not really a relevant criticism. And even if it were, it doesn't refute any criticism of Haskell that you are able to point out unrelated shortcomings in an unrelated language.Also, the example of hello world doesn't show much about complexity. After all, in Haskell it's just:
main = putStr "Hello World"