我终于弄清楚了如何生成一个随机数,但是编译器仍然抱怨我的代码。

码:

type Quot   = Integer

sign (p,q,g) (x,pub) d =
       do k <- randomRIO(1,q-1 :: Integer)
   ki <- kinv k q
   r <- g^k `mod` p
   s <- (160 + x*r)*ki mod q
   return (r,s)

kinv :: Integer -> Quot -> Integer
kinv k q =
   do (d,t,s) <- gcdE(q,k)
      return s

gcdE(a,0) = (a,1,0)
gcdE(a,b) = (d,t,s - q*t)
    where r = a `mod` b
         q = a `div` b
        (d,s,t) = gcdE(b,r)


错误信息:

crypt.hs:24:7:
Couldn't match expected type `Integer' against inferred type `m a'
In a stmt of a 'do' expression: ki <- kinv k q
In the expression:
    do { k <- randomRIO (1, q - 1 :: Integer);
         ki <- kinv k q;
         r <- g ^ k `mod` p;
         s <- (160 + x * r) * ki mod q;
         .... }
In the definition of `sign':
    sign (p, q, g) (x, pub) d
           = do { k <- randomRIO (1, q - 1 :: Integer);
                  ki <- kinv k q;
                  r <- g ^ k `mod` p;
                  .... }

crypt.hs:37:10:
Couldn't match expected type `Integer'
       against inferred type `(Quot, Quot, b)'
In a stmt of a 'do' expression: (d, t, s) <- gcdE (q, k)
In the expression:
    do { (d, t, s) <- gcdE (q, k);
         return s }
In the definition of `kinv':
    kinv k q
           = do { (d, t, s) <- gcdE (q, k);
                  return s }


我想要的是变量k取0

最佳答案

由于有关kinvgcdE的内容并不复杂,因此它们都不应该包含任何do<-return

同样,您不需要(也不能)使用<-来获取kinvgcdE的结果。任何算术运算符也是如此。只需使用let result = non-monadic operation,而不是result <- non-monadic operation

10-04 23:38