An argument of type non-variable in a constraint when using the >> = operator

I have this simple code:

module Matrix where

matrix :: a -> (Int, Int) -> [[a]]
matrix x (width, height) = replicate height (replicate width x)

mapMatrix :: (a -> b) -> [[a]] -> [[b]]
mapMatrix f m = map (map f) m

When I do this:

mapMatrix (+1) (matrix 0 (2,2))

I get, as expected:

[[1,1], [1,1]]

I probably do not understand the monad and / or operator >>=, but I expected the following to have the same result:

matrix 0 (2,2) >>= mapMatrix (+1)

Instead, I get:

An argument without a type variable in a constraint is: Num [b] (Use FlexibleContexts to allow this) When checking the type to be deduced This is :: forall b. (Num [b], Num b) => [[b]]

How can I write mapMatrix (+1) (matrix 0 (2,2))using monads, so I can read and write code from left to right, and not from the inside, because, as you can imagine, I plan to use mapMatrixa lot on the same matrix, something like:

matrix ... >>= mapMatrix ... >>= mapMatrix .. >>= ...
+4
1

, . , (&) :: a -> (a -> b), Data.Function.

matrix ... & mapMatrix ... & mapMatrix .. & ...

,

(>>=) :: m a -> (a -> m b) -> m b

m s.

, , , : Identity. / .

module Matrix where

import Data.Functor.Identity

matrix :: a -> (Int, Int) -> Identity [[a]]
matrix x (width, height) = Identity $ replicate height (replicate width x)

mapMatrix :: (a -> b) -> [[a]] -> Identity [[b]]
mapMatrix f m = Identity $ map (map f) m

:

runIdentity (matrix ... >>= mapMatrix ... >>= mapMatrix .. >>= ...)
+5

Source: https://habr.com/ru/post/1674262/


All Articles