I've began studying Monads by implementing a simple example, but my Monad instance does not compile.
I want to do something like:
add5 7 >>= add7
This code must return 19 [ (5 + 7) >>= (12+7) ]
The code i've implemented is:
newtype MyType a = MyType ( a -> a)
instance Monad MyType where
MyType comm >>= comm2 = MyType (\inp -> let
value = comm inp
MyType comm2' = comm2
in comm2' value)
return x = MyType (\input -> input)
add5 :: MyType Integer
add5 = MyType (\inp -> inp + 5)
add7 :: MyType Integer
add7 = MyType (\inp -> inp + 7)
When i call add5
and add7
without using bind operator (by commenting Monad instance block), it works:
main = do
let MyType x = add5
let MyType y = add7
putStrLn $ show $ x $ y 7
The output errors are:
new1.hs:5:94:
Couldn't match expected type `a' with actual type `b'
`a' is a rigid type variable bound by
the type signature for
>>= :: MyType a -> (a -> MyType b) -> MyType b
at new1.hs:4:9
`b' is a rigid type variable bound by
the type signature for
>>= :: MyType a -> (a -> MyType b) -> MyType b
at new1.hs:4:9
In the first argument of `comm', namely `inp'
In the expression: comm inp
In an equation for `value': value = comm inp
new1.hs:6:97:
Couldn't match expected type `MyType t0'
with actual type `a -> MyType b'
In the expression: comm2
In a pattern binding: MyType comm2' = comm2
In the expression:
let
value = comm inp
MyType comm2' = comm2
in comm2' value