Say I've written the following amazin piece of code:
func = do
a <- Just 5
return a
It's pretty pointless, I know. Here, a
is 5
, and func
returns Just 5
.
Now I rewrite my awesome (yet pointless) function:
func' = do
a <- Nothing
return a
This function returns Nothing
, but what the heck is a
? There's nothing to extract from a Nothing
value, yet the program doesn't whine when I do something like this:
func'' = do
a <- Nothing
b <- Just 5
return $ a+b
I just have a hard time seeing what actually happens. What is a
? In other words: What does <-
actually do? Saying it "extracts the value from right-side and binds it to the left-side" is obviously over-simplifying it. What is it I'm not getting?
Thanks :)
The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so.
In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.
For instance, you might describe a weather enum that lists sunny, windy, and rainy as cases, but has an associated value for cloudy so that you can store the cloud coverage. Or you might describe types of houses, with the number of bedrooms being an associated integer.
Enum raw values To set a value to your enum, you need to assign a data type to it. In our case above, we are using a type of String . Each raw value for our enum case must be a unique string, character, or value of any integer or floating-point type. This means the value for the two case statements cannot be the same.
Let's try and desugar the do-notation of that last example.
func'' = Nothing >>= (\a -> Just 5 >>= (\b -> return $ a+b))
Now, let's see how >>= is defined for Maybe. It's in the Prelude:
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= k = Nothing
return = Just
fail s = Nothing
So Nothing >>= foo
is simply Nothing
The answer lies in the definition of the Monad
instance of Maybe
:
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
(Just _) >> k = k
Nothing >> _ = Nothing
return = Just
Your func''
translates to:
Nothing >>= (\a -> (Just 5 >>= (\b -> return (a+b))))
From the definition of (>>=)
you can see that the first Nothing
is just threaded through to the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With