Haskell中的类型错误

Pau*_*ers 2 haskell type-conversion

我收到以下错误:

exercise-2-2.hs:15:49:
    Couldn't match expected type `Double' with actual type `Int'
    In the fourth argument of `regularPolygonHelper', namely `theta'
    In the expression: regularPolygonHelper n s 0 theta r
    In an equation for `regularPolygon':
        regularPolygon n s
          = regularPolygonHelper n s 0 theta r
          where
              r = s / 2.0 * (sin (pi / n))
              theta = (2.0 * pi) / n
Run Code Online (Sandbox Code Playgroud)

在以下代码中:

data Shape = Rectangle Side Side
           | Ellipse Radius Radius
           | RTTriangle Side Side
           | Polygon [Vertex]
    deriving Show

type Radius = Float
type Side   = Float
type Vertex = (Float, Float)

square s = Rectangle s s
circle r = Ellipse r r

regularPolygon :: Int -> Side -> Shape
regularPolygon n s = regularPolygonHelper n s 0 theta r
    where r     = s / 2.0 * (sin (pi / n))
          theta = (2.0 * pi) / n

regularPolygonHelper :: Int -> Side -> Int -> Double -> Double -> Shape
regularPolygonHelper 0 s i theta r = Polygon []
regularPolygonHelper n s i theta r = 
    (r * cos (i * theta), r * sin (i * theta)) : 
        (regularPolygonHelper (n - 1) s (i + 1) theta r)
Run Code Online (Sandbox Code Playgroud)

为什么是这样?不是(2.0 * pi) / n双倍?

fuz*_*fuz 7

Haskell在不同的数字类型之间没有自动转换.你必须手工完成这个.在你的情况下,(2.0 * pi) / fromIntegral n会做的伎俩.(你必须在你想要进行演员表的所有其他地方添加这个)原因是,隐式转换会使类型推断更难,恕我直言,类型推断比自动转换更好.

  • 自动转换也可能导致精度损失,这可能是追踪的另一个可能的头痛.总的来说,我认为在混合数字类型时,显式优于隐式. (2认同)