data Plane = Plane { point :: Point, normal :: Vector Double }
data Sphere = Sphere { center :: Point, radius :: Double }
class Shape s where
intersect :: s -> Ray -> Maybe Point
surfaceNormal :: s -> Point -> Vector Double
Run Code Online (Sandbox Code Playgroud)
我也做了两个Plane和Sphere实例Shape.
我试图将球体和平面存储在同一个列表中,但它不起作用.据我所知,它不应该工作,因为Sphere和Plane两种不同的类型,但他们的两个实例Shape,所以它不应该工作?如何在列表中存储形状和平面?
shapes :: (Shape t) => [t]
shapes = [ Sphere { center = Point [0, 0, 0], radius = 2.0 }, …Run Code Online (Sandbox Code Playgroud) 我试图了解Haskell中面向对象的样式编程,知道由于缺乏可变性,事情会有所不同.我玩过类型类,但我对它们的理解仅限于它们作为接口.所以我编写了一个C++示例,它是具有纯基础和虚拟继承的标准菱形.Bat继承Flying和Mammal,以及Flying和Mammal继承Animal.
#include <iostream>
class Animal
{
public:
virtual std::string transport() const = 0;
virtual std::string type() const = 0;
std::string describe() const;
};
std::string Animal::describe() const
{ return "I am a " + this->transport() + " " + this->type(); }
class Flying : virtual public Animal
{
public:
virtual std::string transport() const;
};
std::string Flying::transport() const { return "Flying"; }
class Mammal : virtual public Animal
{
public: …Run Code Online (Sandbox Code Playgroud) 我们经常使用类型依赖来模拟子类型关系.
例如:
当我们想在OOP中表达Animal,Reptile和Aves之间的子类型关系时:
abstract class Animal {
abstract Animal move();
abstract Animal hunt();
abstract Animal sleep();
}
abstract class Reptile extends Animal {
abstract Reptile crawl();
}
abstract class Aves extends Animal {
abstract Aves fly();
}
Run Code Online (Sandbox Code Playgroud)
我们可以将上面的每个抽象类翻译成Haskell中的一个类型类:
class Animal a where
move :: a -> a
hunt :: a -> a
sleep :: a -> a
class Animal a => Reptile a where
crawl :: a -> a
class Animal a => Aves a where
fly :: a -> …Run Code Online (Sandbox Code Playgroud) 让模块进行抽象Area操作(定义不好)
class Area someShapeType where
area :: someShapeType -> Float
-- module utilities
sumAreas :: Area someShapeType => [someShapeType]
sumAreas = sum . map area
Run Code Online (Sandbox Code Playgroud)
让后验明确的形状类型模块(良好或可接受的定义)
data Point = Point Float Float
data Circle = Circle Point Float
instance Surface Circle where
surface (Circle _ r) = 2 * pi * r
data Rectangle = Rectangle Point Point
instance Surface Rectangle where
surface (Rectangle (Point x1 y1) (Point x2 y2)) = abs $ (x2 - x1) …Run Code Online (Sandbox Code Playgroud)