ошибка типа в Хаскеле - PullRequest
       14

ошибка типа в Хаскеле

2 голосов
/ 23 августа 2011

Я получаю следующую ошибку:

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

в следующем коде:

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)

Почему это? Разве (2.0 * pi) / n не двойной?

Ответы [ 2 ]

7 голосов
/ 23 августа 2011

Haskell не имеет автоматического преобразования между различными числовыми типами. Вы должны сделать это вручную. В вашем случае, (2.0 * pi) / fromIntegral n сделает свое дело. (Вы должны добавить это во всех других местах, где вы хотите иметь приведение). Причина этого в том, что неявное преобразование сделает вывод типов намного сложнее, ИМХО, лучше иметь вывод типов, чем автоматическое преобразование.

2 голосов
/ 23 августа 2011

лучше не смешивать столько типов вот версия, которая компилируется до сих пор:


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

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

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 / fromIntegral n))
          theta = (2.0 * pi) / fromIntegral n

regularPolygonHelper :: Int -> Side -> Int -> Double -> Double -> Shape
regularPolygonHelper 0 s i theta r = Polygon []
regularPolygonHelper n s i theta r = 
    let Polygon rPoly = regularPolygonHelper (n - 1) s (i + 1) theta r in
    Polygon ((r * cos (fromIntegral i * theta), r * sin (fromIntegral i * theta)) : rPoly)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...