Haskell错误:无法将预期类型`Bool'与推断类型`IO b'匹配

And*_*röm 0 monads haskell boolean

我不明白问题是什么.'a'不是bool,不应该是bool.那么为什么要预期布尔?

码:

probablyPrime n 0 = False
probablyPrime n t =
      do a <- randomRIO(3, n-1 :: Integer)      
         let comp = defComp(a,n)     
         let ret  = (not comp) && (probablyPrime n t-1)
         return ret


defComp a n = xcon1 && xcon2
where (s,m) = findsm n
      x = a^m `mod` n
      xcon1 = x /= 1 || x /= n-1
      xcon2 = comploop x n s


comploop x n 0 = False
comploop x n s = x1 || (comploop x n (s-1))
    where x1 = (x^2 `mod` n) == 1


findsm n = (s,m)
where m = findm n
      s = n/m


findm n = m
  where f = (logBase 2 n) - (truncate (logBase 2 n))
        m' = 2^f
        m = m_ify m'


m_ify m | m mod 1 == 0 = m
     | otherwise = m_ify (m*2)
Run Code Online (Sandbox Code Playgroud)

错误:

Couldn't match expected type `Bool' against inferred type `IO b'
In a stmt of a 'do' expression:
    a <- randomRIO (3, n - 1 :: Integer)
In the expression:
    do { a <- randomRIO (3, n - 1 :: Integer);
         let comp = defComp ...;
         let ret = (not comp) && (probablyPrime n t - 1);
         return ret }
In the definition of `probablyPrime':
    probablyPrime n t
                    = do { a <- randomRIO (3, n - 1 :: Integer);
                           let comp = ...;
                           let ret = ...;
                           .... }
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 5

probablyPrime n 0 = False
Run Code Online (Sandbox Code Playgroud)

这告诉haskell返回类型probablyPrimeBool.但是在第二种情况下,您正在处理monad并返回IO Bool,因此类型不匹配.

更改Falsereturn False,它会工作.

你也必须改变

let ret  = (not comp) && (probablyPrime n t-1)
Run Code Online (Sandbox Code Playgroud)

prob <- probablyPrime n (t-1)
let ret = (not comp) && prob
Run Code Online (Sandbox Code Playgroud)

或类似的东西

ret <- liftM ((not comp) &&) (probablyPrime n (t-1))
Run Code Online (Sandbox Code Playgroud)

正如Andrew Jaffe指出的那样.