
Hi, On 2015-03-26 11:06, Shishir Srivastava wrote:
After reading and re-reading the haskell tutorials I don't happen to see a very convincing or appealing reason for having these data types.
First of all, only one of them is a type (or a 'type constructor'): "Maybe". "Just" on the other hand is a "data constructor", i.e. "Just 'x'" will yield a value of type "Maybe Char".
Can anyone please explain where Maybe and Just provide the sort of functionality that cannot be achieved in other languages which don't have these kind.
They don't provide anything which other languages cannot achieve. 'Maybe' values merely indicate that you *maybe* get a value. This is useful for functions which might not be able to yield a meaningful result. Consider a 'safeHead' function which works like 'head', returning the first element of a given list. What should it do for empty lists? Something like 'Maybe' is useful because it 1. Makes potential errors clearly visible in the type system: If a function returns a 'Maybe Char', you know that it possible won't yield a Char (but rather 'Nothing'). Raising an exception is totally opaque to the caller. 2. Clearly separates the values which might represent failures from those which don't. Contrast this with e.g. Java, where every object of every type can be null. If every value is potentially 'null', you either have to check using if() everywhere or use assertions. With 'Maybe', the null'ness can be asserted by the compiler. 3. Relieves other types from having an explicit 'Invalid' value. Consider: data Color = Red | Green | Blue | Invalid -- Parses a color string; yields 'Invalid' if the string is malformed parseColor :: String -> Color parseColor = undefind With a setup like this, *every* code dealing with 'Color' values will have to be able to handle 'Invalid' colors. It ripples through the system. OTOH, something like data Color = Red | Green | Blue -- Parses a color string; yields 'Nothing' if the string is malformed parseColor :: String -> Maybe Color parseColor = undefined Clearly separates the valid colors, such that only the caller of 'parseColor' only has to check for 'Just x' values - and if it got one, it can pass the 'x' value to other code. For what it's worth, other languages have similiar concepts. For instance, C++ programmers can use 'boost::optional' (which, alas, didn't make it into C++14). -- Frerich Raabe - raabe@froglogic.com www.froglogic.com - Multi-Platform GUI Testing