嗯,我确实认识到我对haskell感到困惑,这是我第一个周末.
我只是想知道以下设计的OO级Point2D

应该用Haskell编写如下:
import Prelude hiding ( sum )
-- ...............................................................
-- "class type" : types belonging to this family of types
-- must implement distance and sum functions
-- ...............................................................
class PointFamily p where
-- p is a type of this family, not a point
distance :: p -> p -> Float -- takes two things of type p and returns a Real
sum :: p -> p -> p -- takes two things of type p and returns a p thing
-- ...............................................................
-- data type: Point2D
-- a new type with x and y coordinates
-- ...............................................................
data Point2D = Point2D { x :: Float , y :: Float }
deriving (Show) -- it is "showable/printable"
-- ...............................................................
-- Point2D belongs to PointFamily, so let's say it and
-- how to compute distance and sum for this type
-- ...............................................................
instance PointFamily Point2D where
-- ............................................................-
distance p1 p2 = sqrt (dx*dx + dy*dy)
where
dx = (x p1) - (x p2)
dy = (y p1) - (y p2)
-- ............................................................-
sum p1 p2 = Point2D { x = (x p1)+(x p2), y = (y p1)+(y p2) }
-- ...............................................................
-- global constant
-- ...............................................................
origin = Point2D 0.0 0.0
-- ...............................................................
-- main
-- ...............................................................
main = do
putStrLn "Hello"
print b
print $ distance origin b
print $ sum b b
where
b = Point2D 3.0 4.0
Run Code Online (Sandbox Code Playgroud)
是的,我知道我不应该尝试在Haskell中"思考OOP",但是......好吧,1)这需要很长时间,2)在实践中我猜你会发现几个OOP设计需要重写在哈斯克尔
lef*_*out 10
首先:确实,你应该尽量不在Haskell中"思考OOP"!
但是你的代码根本不是OOP.如果您开始尝试虚拟继承等,那将是OO,但在此示例中,更多的是OO实现恰好类似于明显的Haskell实现.
只是,应该强调的是,类型类PointFamily与数据类型实际上没有任何特定的1:1关系Point2D,就像它们在OO类中的捆绑一样.实际上,您可以为可以想象的任何类型创建此类的实例.不出所料,以前所有这一切都已经完成; 最普遍的等价物PointFamily是AffineSpace从vector-spaces包.这是更普遍的,但原则上有很多相同的目的.
| 归档时间: |
|
| 查看次数: |
583 次 |
| 最近记录: |