苍鹭';haskell中的s方法

苍鹭';haskell中的s方法,haskell,sqrt,Haskell,Sqrt,我在heron方法的代码中遇到了被零除的异常,我在这里有点迷茫 epsilon:: Integral a => a epsilon = 1 heron:: Integral a => a -> a heron r = help 0 where help x | abs (heron' x - heron' (x + 1)) < epsilon = heron' (x + 1) | otherwise

我在heron方法的代码中遇到了被零除的异常,我在这里有点迷茫

epsilon:: Integral a => a
epsilon = 1

heron:: Integral a => a -> a
heron r = help 0
  where
    help x
      | abs (heron' x - heron' (x + 1)) < epsilon = heron' (x + 1)
      | otherwise                                 = help (x + 1)

    heron' 0 = 1
    heron' x = (1 `div` 2) * (heron' (x-1) + (r `div` heron' (x-1)))
epsilon::积分a=>a
ε=1
积分a=>a->a
heron r=帮助0
哪里
帮助x
|abs(鹭'x-heron'(x+1))
在这段代码中,我有什么建议可以解决这个问题


(1`div`2)
肯定是个问题,但是我需要写什么来代替呢?

如果需要这种除法,您可能希望使用
(/)
而不是
div
分数
而不是
整数
。因此:

epsilon:: Fractional a => a
epsilon = 1

heron:: (Fractional a, Ord a) => a -> a
heron r = help 0
  where
    help x
      | abs (heron' x - heron' (x + 1)) < epsilon = heron' (x + 1)
      | otherwise                                 = help (x + 1)

    heron' 0 = 1
    heron' x = (1 / 2) * (heron' (x-1) + (r / heron' (x-1)))
ε:分数a=>a ε=1 苍鹭::(分数a,Ord a)=>a->a heron r=帮助0 哪里 帮助x |abs(鹭'x-heron'(x+1))
那么,
(1`div`2)*foo
可以通过
foo`div`2
更准确地计算出来。但也许使用浮点或有理数会更好…?我尝试使用小数类型,以便可以写(1/2),但在函数中使用<符号时出现错误..显示您的尝试。@greentea,您可能需要在
小数
约束中添加
Ord
约束。谢谢大家,我添加了约束,现在函数运行良好!