haskell polymorphism and lists

后端 未结 6 1003
温柔的废话
温柔的废话 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:29

    How to deal with a heterogeneous list of shapes in Haskell — Abstract polymorphism with type classes: http://pastebin.com/hL9ME7qP via @pastebin

    CODE:

    {-# LANGUAGE GADTs #-}
    
    class Shape s where
     area :: s -> Double
     perimeter :: s -> Double
    
    data Rectangle = Rectangle {
     width :: Double,
     height :: Double
    } deriving Show
    
    instance Shape Rectangle where
     area rectangle = (width rectangle) * (height rectangle)
     perimeter rectangle = 2 * ((width rectangle) + (height rectangle))
    
    data Circle = Circle {
     radius :: Double
    } deriving Show
    
    instance Shape Circle where
     area circle = pi * (radius circle) * (radius circle)
     perimeter circle = 2.0 * pi * (radius circle)
    
    r=Rectangle 10.0 3.0 
    c=Circle 10.0
    list=[WrapShape r,WrapShape c]
    
    data ShapeWrapper where
     WrapShape :: Shape s => s -> ShapeWrapper
    
    getArea :: ShapeWrapper -> Double
    getArea (WrapShape s) = area s
    
    getPerimeter :: ShapeWrapper -> Double
    getPerimeter (WrapShape s) = perimeter s
    
    areas = map getArea list
    perimeters = map getPerimeter list
    

提交回复
热议问题