简体   繁体   English

如何建模函数式编程中的继承关系

[英]How to model inheritance relationship in Functional Programming

Object Oriented programming paradigm uses inheritance to model relationships between entities that follow Generalization-Specialization relationship.面向对象编程范式使用继承来建模遵循泛化-专业化关系的实体之间的关系。 Here, a Base class is used to encapsulate the common (General) attributes and behavior of a set of entities and the Derived Classes extend the base class by adding additional attributes and/or adding/modifying existing behavior.这里,基类用于封装一组实体的公共(通用)属性和行为,派生类通过添加附加属性和/或添加/修改现有行为来扩展基类。

As someone new to Functional Programming, I need guidance on modeling such relationships in functional languages like F#.作为函数式编程的新手,我需要有关在 F# 等函数式语言中对此类关系进行建模的指导。

eg what would be the best approach to model a simple situation like the following:例如,模拟如下简单情况的最佳方法是什么:

abstract class Tutorial { 
  private String topic;
  abstract public void learn();
}

class VideoTutorial extends Tutorial {
  private float duration;
  public void learn () {
    System.out.println ("Watch Video");
  }
}

class PDFTutorial extends Tutorial {
  private int pageCount;
  public void learn () {
    System.out.println ("Read PDF");
  }
}

and then later use a collection of Tutorials and call learn to observe polymorphic behavior.然后使用一组教程并调用学习来观察多态行为。

In the functional design, you think about things a bit differently, so the ideas will not map perfectly.在功能设计中,您对事物的看法有点不同,因此这些想法​​不会完美映射。 Typically, functional design focuses more on data types that express the entities you are working with.通常,功能设计更侧重于表达您正在使用的实体的数据类型。 In your case, you could define TutorialKind which is either video or PDF using a discriminated union and Tutorial would then be a record that consits of a kind and its topic:在您的情况下,您可以定义TutorialKind ,它是使用可区分联合的视频或 PDF,然后Tutorial将成为包含一种类型及其主题的记录:

type TutorialKind = 
  | VideoTutorial of duration:float
  | PDFTutorial of pageCount:int

type Tutorial = 
  { Kind : TutorialKind
    Topic : string }

Note that this keeps just the data about tutorials.请注意,这仅保留有关教程的数据。 Any functionality can be implemented in functions that pattern match on the kind of the tutorial:任何功能都可以在与教程类型匹配的函数中实现:

let learn tutorial = 
  match tutorial.Kind with
  | VideoTutorial _ -> printfn "Watch video"
  | PDFTutorial _ -> printfn "Read PDF"

Note that this is extensible in a different direction than the OO version.请注意,这可以在与 OO 版本不同的方向上进行扩展。 In OO, you can easily add new subclasses;在 OO 中,您可以轻松添加新的子类; here you can easily add new functions.在这里您可以轻松添加新功能。 In practice, functional people are usually happy with this change, but F# is a mixed language and if you need "OO-style extensibility", you can easily use interfaces.在实践中,函数式人员通常对这种变化感到满意,但 F# 是一种混合语言,如果您需要“OO 风格的可扩展性”,您可以轻松使用接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM