I was reading a submission on exercism.io in which someone suggested that
concat (replicate n str)
could be alternatively expressed as:
[1..n] >>= return str
Without going into all the debate that then ensued on this subject: I'm looking for an explanation in complete layman's terms of why/how this works.
In particular, after trying to recast this in my mind, I thought it might be somewhat analogous to:
fmap (return char) [1..3]
But what I don't then understand is why
[1..n] >>= return 'M'
is an error, where
[1..n] >>= return "M"
is good.
Can any persons who are really clued up in Haskell walk me through how this all works?
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.
In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0.
The return statement may or may not return anything for a void function, but for a non-void function, a return value must be returned. Syntax: return[expression];
[1..n] >>= return str
Here return
is from the function monad ((->) a
) so the above is equivalent to
[1..n] >>= const str
in which const
is a function that ignores its parameter and always returns str
and >>=
is the bind operator for the list monad, which is the same as concatMap
so we get
concatMap (const str) [1..n]
which essentially replaces each list element with str
and then concatenates them.
As to why [1..n] >>= return 'M'
is an error: it reduces to concatMap (const 'M') [1..n]
but the parameter to concatMap
must return a list and 'M'
is not a list, whereas "M"
(which is equivalent to ['M']
) is.
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