Euclid算法的递归实现 - 类型错误

Wea*_*ped 1 haskell functional-programming

这是代码(Euclid的GCD算法).当然有Prelude.gcd一些练习我正在实施自己的练习.

selfGCD :: Integral f => f -> f -> f  
selfGCD a b = if b == 0 then
        return a
    else 
        return (selfGCD a (mod a b))
Run Code Online (Sandbox Code Playgroud)

使用ghci,我收到以下错误:

two.hs:32:25:  
Couldn't match type `f' with `m0 f'  
  `f' is a rigid type variable bound by  
      the type signature for selfGCD :: Integral f => f -> f -> f  
      at two.hs:31:1  
In the return type of a call of `return'  
In the expression: return a  
In the expression:  
  if b == 0 then return a else return (selfGCD a (mod a b))  

two.hs:34:25:  
Couldn't match type `f' with `m1 f'  
  `f' is a rigid type variable bound by  
      the type signature for selfGCD :: Integral f => f -> f -> f  
      at two.hs:31:1  
In the return type of a call of `return'  
In the expression: return (selfGCD a (mod a b))  
In the expression:  
  if b == 0 then return a else return (selfGCD a (mod a b))  
Run Code Online (Sandbox Code Playgroud)

我该如何纠正这个问题?

Dan*_*her 9

放弃returns.

在Haskell中,return是类型的函数

return :: Monad m => a -> m a
Run Code Online (Sandbox Code Playgroud)

而不是return你从命令式语言中知道的运算符.

因此,使用returns,实现具有类型

selfGCD :: (Integral a, Monad m) => a -> a -> m a
Run Code Online (Sandbox Code Playgroud)

与类型签名相反.