S
Silvio
Yeah, I hoped you'd give a short example of use in Haskell/Scala, to show
what a language could make even simpler about that.
Well, here is an example in Scala:
Let's assume we have a getString defined as:
def getString(s : String) : Option[String] =
{
if (s.reverse == s) Some(s.toLowerCase)
else None
}
then it will return either Some(r) where r is a String or it will return
None indicating failure.
We could call it like this:
val t : Option[String] = getString(s)
or a bit shorter:
val t = getString(s)
and let the compiler figure out the type of t (I could have dropped the
Option[String] return type from the getString definition the same way).
Now we could use pattern matching against t:
t match
{
case Some(r) => println("Success, return value is: " + r)
case None => println("Failure")
}
However, since an Option[T] is a monad like most containers in Scala are
we have shorthand notations for chaining operations on it like map,
foreach, forall, exists etc.
Example1: t.map(_.length) will return an Option[Int] which is None if t
is None or Some(r.length) if t is Some(r)
Example2: t.foreach(println(_)) will print r if t is Some(r) and do
nothing if t is None.
Pattern matching is an incredible powerfull and flexible language
feature in Scala and clearly lays out how Option[T] can be treated. In
practice we rarely use it on an Option because the shorthand notations
cover almost every practical use.
Gr. Silvio
I should have said "short cuts" instead of "shorthand notations". They
are not notational magic but simple library functions.