嗨,我正在尝试编写一些基本代码来实现Bresenham算法,但是我只能尝试使用round和/。我的代码是:
bresenhamAlgorithm :: Coord -> Coord -> Int -> Int
bresenhamAlgorithm (x1, y1) (x2, y2) x'= round $ (fromIntegral ((y2 -
y1) * (x' - x1)) / fromIntegral (x2 - x1)) + y1我不断地看到No instance for (Fractional Int) arising from a use of ‘/’和No instance for (RealFrac Int) arising from a use of ‘round’错误的发生。我不明白,因为我相信fromIntegral会把分子和分母转换成分式,这样就可以使用/运算了?
发布于 2018-05-05 13:36:56
我不明白,因为我相信fromIntegral会把分子和分母转换成分式,这样就可以使用/运算了?
是的,你的理解基本上是正确的,但你做了一个小疏忽。
下面是您的代码的格式略有不同:
bresenhamAlgorithm :: Coord -> Coord -> Int -> Int
bresenhamAlgorithm (x1, y1) (x2, y2) x'= round $
(
fromIntegral ((y2 - y1) * (x' - x1))
/ fromIntegral (x2 - x1)
) + y1这是(因为+绑定比$更强),相当于:
bresenhamAlgorithm :: Coord -> Coord -> Int -> Int
bresenhamAlgorithm (x1, y1) (x2, y2) x'= round (
(
fromIntegral ((y2 - y1) * (x' - x1))
/ fromIntegral (x2 - x1)
) + y1)这里的问题实际上既不是round,也不是/,而是您的+ y1。因为已知y1是Int,所以类型检查器试图统一
fromIntegral ((y2 - y1) * (x' - x1)) / fromIntegral (x2 - x1)使用Int,当然会失败,因为Int不允许使用/。
解决方案是添加另一个fromIntegral
bresenhamAlgorithm :: Coord -> Coord -> Int -> Int
bresenhamAlgorithm (x1, y1) (x2, y2) x'= round $
(
fromIntegral ((y2 - y1) * (x' - x1))
/ fromIntegral (x2 - x1)
) + fromIntegral y1 -- we need y1 as a fractional或者,您也可以将+ y1之前的所有内容--包括round --都封装在括号中,这也是可行的。
因为fromIntegral实际上可以将整数类型转换为任何数字类型.包括他们自己。因此,在本例中,由于表达式是如何编写的,打字机推断您的意思是fromIntegral将Int转换为.Int又来了。这不是你的意思,但编译器不知道。
如果我们添加一个小助手函数:
toDouble :: Int -> Double
toDouble = fromIntegral并在您的定义中使用它而不是fromIntegral
bresenhamAlgorithm :: Coord -> Coord -> Int -> Int
bresenhamAlgorithm (x1, y1) (x2, y2) x'= round $
(
toDouble ((y2 - y1) * (x' - x1))
/ toDouble (x2 - x1)
) + y1为了强制转换,我们实际上得到了一个更有用的错误消息:
• Couldn't match expected type ‘Double’ with actual type ‘Int’
• In the second argument of ‘(+)’, namely ‘y1’
In the second argument of ‘($)’, namely
‘(toDouble ((y2 - y1) * (x' - x1)) / toDouble (x2 - x1)) + y1’
In the expression:
round
$ (toDouble ((y2 - y1) * (x' - x1)) / toDouble (x2 - x1)) + y1
) + y1
^^https://stackoverflow.com/questions/50189967
复制相似问题