相关疑难解决方法(0)

不同类型的列表?

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)

我也做了两个PlaneSphere实例Shape.

我试图将球体和平面存储在同一个列表中,但它不起作用.据我所知,它不应该工作,因为SpherePlane两种不同的类型,但他们的两个实例Shape,所以它不应该工作?如何在列表中存储形状和平面?

shapes :: (Shape t) => [t]
shapes = [ Sphere { center = Point [0, 0, 0], radius = 2.0 }, …
Run Code Online (Sandbox Code Playgroud)

haskell

39
推荐指数
2
解决办法
7443
查看次数

Haskell中面向对象的编程

我试图了解Haskell中面向对象的样式编程,知道由于缺乏可变性,事情会有所不同.我玩过类型类,但我对它们的理解仅限于它们作为接口.所以我编写了一个C++示例,它是具有纯基础和虚拟继承的标准菱形.Bat继承FlyingMammal,以及FlyingMammal继承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)

c++ oop haskell functional-programming virtual-functions

10
推荐指数
2
解决办法
1543
查看次数

haskell中的类型依赖与OOP中的子类型有什么区别?

我们经常使用类型依赖来模拟子类型关系.

例如:

当我们想在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)

haskell typeclass subtype subtyping

8
推荐指数
1
解决办法
344
查看次数

Haskell中的异构多态(正确方式)

让模块进行抽象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)

polymorphism haskell types class heterogeneous

3
推荐指数
3
解决办法
390
查看次数