haskell polymorphism and lists

后端 未结 6 1068
温柔的废话
温柔的废话 2021-02-02 13:45

Suppose I have the following:

class Shape a where
    draw a :: a -> IO ()

data Rectangle = Rectangle Int Int

instance Shape Rectangle where
    draw (Recta         


        
6条回答
  •  情深已故
    2021-02-02 14:46

    A variant of Ganesh's solution using the existential quantification syntax instead.

    {-# LANGUAGE ExistentialQuantification #-}
    class IsShape a where
        draw :: a -> String
    
    data Rectangle = Rectangle Int Int
    
    instance IsShape Rectangle where
        draw (Rectangle length width) = ""
    
    data Circle = Circle Int Int
    
    instance IsShape Circle where
        draw (Circle center radius) = ""
    
    data Shape = forall a. (IsShape a) => Shape a
    
    shapes = [Shape (Circle 5 10), Shape (Circle 20 30), Shape (Rectangle 10 15)]
    

提交回复
热议问题