Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell FlatMap

I am a beginner interested in Haskell, and I have been trying to implement the flatmap (>>=) on my own to better understand it. Currently I have

flatmap :: (t -> a) -> [t] -> [a]  
flatmap _ [] = []  
flatmap f (x:xs) = f x : flatmap f xs  

which implements the "map" part but not the "flat".
Most of the modifications I make result in the disheartening and fairly informationless

Occurs check: cannot construct the infinite type: a = [a]  
    When generalising the type(s) for `flatmap' 

error.

What am I missing?

like image 500
Mantas Vidutis Avatar asked Jun 07 '10 02:06

Mantas Vidutis


People also ask

Is monad a flatMap?

bind (or flatMap ) and unit (the constructor) are all it takes to be considered a monad.

Is bind the same as flatMap?

Bind is flatmap in the case of lists. Bind is way more generic than just the list monad, and the name "flatmap" doesn't apply to most other monads -- most of which are not List. Yes, bind is just flatMap.

Why is flatMap called flatMap?

If you use a function that returns a list of values in map() operation you get a Stream of Stream and by using flatMap you can convert that to Stream of values. In short, you can combine several small lists of values into a big list of values using flatMap(). It's called flatMap() because it flattens the Stream.

What is >> in Haskell?

Essentially, a >> b can be read like "do a then do b , and return the result of b ". It's similar to the more common bind operator >>= .


1 Answers

An error like this happens when the type signature you specify does not match the actual type of the function. Since you didn't show the code that causes the error, I have to guess, but I presume you changed it to something like this:

flatmap _ [] = []  
flatmap f (x:xs) = f x ++ flatmap f xs

Which as it happens, is perfectly correct. However if you forgot to also change the type signature the following will happen:

The type checker sees that you use ++ on the results of f x and flatmap f xs. Since ++ works on two lists of the same type, the type checker now knows that both expressions have to evaluate to lists of the same type. Now the typechecker also knows that flatmap f xs will return a result of type [a], so f x also has to have type [a]. However in the type signature it says that f has type t -> a, so f x has to have type a. This leads the type checker to conclude that [a] = a which is a contradiction and leads to the error message you see.

If you change the type signature to flatmap :: (t -> [a]) -> [t] -> [a] (or remove it), it will work.

like image 159
sepp2k Avatar answered Sep 21 '22 17:09

sepp2k