私は単純な型クラスを書きましたShape
:
class Shape a where
draw :: a -> IO ()
move :: (Double,Double) -> a -> a
area :: a -> Double
circum :: a -> Double
また、具象型もあり、Circle
この型クラスを次のようにインスタンス化します。Rect
Triangle
data Circle = Circle Point Double deriving (Show)
instance Shape Circle where
draw (Circle centre radius) = putStrLn $ "Circle [" ++ show centre ++ ", " ++ show radius ++ "]"
move (x,y) (Circle centre radius) = Circle (movePoint x y centre) radius
area (Circle _ r) = r ^ 2 * pi
circum (Circle _ r) = 2 * r * pi
movePoint :: Double -> Double -> Point -> Point
movePoint x y (Point x_a y_a) = Point (x_a + x) (y_a + y)
Circle
具体的な型のインスタンスRect
を含む異種リストを操作するために、異種コレクションに関する haskell wiki チュートリアルTriangle
に従い、次のような存在データ型を実装しました。ShapeType
{-# LANGUAGE ExistentialQuantification #-}
data ShapeType = forall a . Shape a => MkShape a
型クラスをShapeType
インスタンス化します。Shape
instance Shape ShapeType where
area (MkShape s) = area s
circum (MkShape s) = circum s
draw (MkShape s) = draw s
move (x,y) (MkShape s) = move (x,y) s -- this does not compile
これで、次のようなコードでこれを使用できます。
rect = Rect (Point 0 0) (Point 5 4)
circle = Circle (Point 4 5) 4
triangle = Triangle (Point 0 0) (Point 4 0) (Point 4 3)
shapes :: [ShapeType]
shapes = [MkShape rect, MkShape circle, MkShape triangle]
main = do
print $ map area shapes
print $ map circum shapes
mapM_ draw shapes
残念ながら、これは行を省略した場合にのみコンパイルされます
move (x,y) (MkShape s) = move (x,y) s
そうしないと、次のコンパイル エラーが発生します。
error:
* Couldn't match expected type `ShapeType' with actual type `a'
`a' is a rigid type variable bound by
a pattern with constructor:
MkShape :: forall a. Shape a => a -> ShapeType,
in an equation for `move'
at C:\\workspace\FPvsOO\src\Lib.hs:102:15-23
* In the expression: move (x, y) s
In an equation for `move': move (x, y) (MkShape s) = move (x, y) s
In the instance declaration for `Shape ShapeType'
* Relevant bindings include
s :: a (bound at C:\\workspace\FPvsOO\src\Lib.hs:102:23)
s
委任呼び出しで使用するためのパターン マッチングによる"抽出" は、他の 3 つのケースでは正常に機能するため、これは私には意味がありません。
ここで何がうまくいかないのですか?
アップデート
この簡単な修正により、コードは期待どおりに機能するようになりました。
instance Shape ShapeType where
area (MkShape s) = area s
circum (MkShape s) = circum s
draw (MkShape s) = draw s
move vec (MkShape s) = MkShape (move vec s)