i'm a newish to Haskell and have this piece of code:
import Control.Monad
data NestedList a = Elem a | List [NestedList a] deriving (Show)
instance Monad NestedList where
return a = List [Elem a]
(List (Elem a: xs)) >>= f = let a' = f a in a' `joinLists` xs
func :: a -> NestedList a
func a = List ([Elem a] ++ [Elem a])
joinLists :: NestedList a -> [NestedList a] -> NestedList a
joinLists (List a) b = List (a ++ b)
main = do let a = List [Elem 1, Elem 2] >>= func
print a
What I am trying to do is to take a List with elements, replicate 1st element of the list and add a tail to this list. So List [Elem 1, Elem 2] would be equal to List [Elem 1, Elem 1, Elem 2]. I know that's not a good example of using Monads, but that's for the sake of learning.
I am getting an error like this:
Couldn't match type 'a' with 'b'
'a' is a rigid type variable bound by
the type signature for
'>>= :: NestedList a -> (a -> NestedList b) -> NestedList b
'b' is a rigid type variable bound by
the type signature for
'>>= :: NestedList a -> (a -> NestedList b) -> NestedList b
Expected type: [NestedList b]
Actual type: [NestedList a]
In the second argument of 'joinLists', namely 'xs'
I understand the error is that it expects a different type variable of NestedList. What is the problem here?
joinLists,a'isElem bbutxsis[Elem a]. The monad bind is(>>=) :: Monad m => m a -> (a -> m b) -> m b- josejuanNestedList a = List [Elem a]and correct,xsis[Elem a] or [NestedList a]. And joinLists takes NestedList a and [NestedList a], so it shouldn't cause a problem. How can I transform[Elem a] to [Elem b]? - Aidas Simkusfhas type(a -> m b), that is where that type variablebcomes from. - Lee Duhema'is of typeElem b, becausef :: a -> NestedList bfor anyb. Even if you only use it withf :: a -> NestedList a,Monadshould work for functions even withaandbbeing different. It is up to you how to createNestedList bout of the remainingNestedList a. Perhaps, applyingfto each element ofxswould work, but that depends on the logic of what you are doing. Also,joinListsdoesn't have a pattern forElem a, so you are going to feel that soon. - Sassa NF