Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

>>= return ... what's going on here?

Tags:

haskell

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?

like image 272
thesunneversets Avatar asked Nov 13 '13 16:11

thesunneversets


People also ask

How do you use a return statement?

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.

What is >> and << in Python?

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.

What is >> mean in Python?

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.

How do you write a return statement in C?

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 Answers

[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.

like image 112
shang Avatar answered Oct 14 '22 06:10

shang