Haskell中一个简单的面向对象的类'Point'

 苦蔷薇1988 发布于 2023-02-13 15:25

嗯,我确实认识到我对haskell感到困惑,这是我第一个周末.

我只是想知道以下设计的OO级Point2D

Point2D的UML设计

应该用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

是的,我知道我不应该尝试在Haskell中"思考OOP",但是......好吧,1)这需要很长时间,2)在实践中我猜你会发现几个OOP设计需要重写在哈斯克尔

1 个回答
  • 首先:确实,你应该尽量不在Haskell中"思考OOP"!

    但是你的代码根本不是OOP.如果您开始尝试虚拟继承等,那将是OO,但在此示例中,更多的是OO实现恰好类似于明显的Haskell实现.

    只是,应该强调的是,类型类PointFamily与数据类型实际上没有任何特定的1:1关系Point2D,就像它们在OO类中的捆绑一样.实际上,您可以为可以想象的任何类型创建此类的实例.不出所料,以前所有这一切都已经完成; 最普遍的等价物PointFamilyAffineSpacevector-spaces包.这是更普遍的,但原则上有很多相同的目的.

    2023-02-13 15:26 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有