I have a type with different fields which looks something like this
data MyType = MyType
{ field1 :: String
, field2 :: Bool
, field3 :: Int }
deriving Show
Also i have a function, which checks, if the field value isn't equal to some value that i don't need.
check :: Eq b => MyType -> (MyType -> b) -> b -> IO (Maybe ())
check base f fail_value = do
case (f base) == fail_value of
True -> do
putStrLn "Bad Bad Bad"
return Nothing
_ -> return . Just $ ()
Now i want to create a list of results of applying check
with different arguments.
let example = MyType [] False 0
let test = check example -- Here is the problem.
let tests = [ test field1 []
, test field2 False
, test field3 0 ]
The type of expressions is supposed to be same, ghci also confirming.
check example field1 [] :: IO (Maybe ())
check example field2 False :: IO (Maybe ())
check example field3 0 :: IO (Maybe ())
But the problem is, that there is the type checking error, despite the type of tests
expression supposed to be [IO (Maybe ())]
. Can you tell me please, why this doesn't work as i think is suppose to work? Thank you so much.
The error from ghci:
Couldn't match type ‘[Char]’ with ‘Bool’
Expected type: MyType -> [Char]
Actual type: MyType -> Bool
Edit
Short : pragma NoMonomorphismRestriction helped.
{-# LANGUAGE NoMonomorphismRestriction #-}
Instead of this.
let example = MyType [] False 0
let tests = [ check example field1 []
, check example field2 False
, check example field3 0 ]
In my actual code I was using something like this:
let example = MyType [] False 0
let test' = check example -- Here it is...
let tests = [ test' field1 []
, test' field2 False
, test' field3 0 ]
And was getting error in type check, with this test' function. Without it, it is actually working fine.
There is some non-intuitive thing in type inference. https://wiki.haskell.org/Monomorphism_restriction
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.