Achieving polymorphism in functional programming

后端 未结 5 1291
我寻月下人不归
我寻月下人不归 2020-12-07 10:52

I\'m currently enjoying the transition from an object oriented language to a functional language. It\'s a breath of fresh air, and I\'m finding myself much more productive t

5条回答
  •  眼角桃花
    2020-12-07 11:02

    Mike, both your approaches are perfectly acceptable, and the pros and cons of each are discussed, as Doc Brown says, in Chapter 2 of SICP. The first suffers from having a big type table somewhere, which needs to be maintained. The second is just traditional single-dispatch polymorphism/virtual function tables.

    The reason that scheme doesn't have a built-in system is that using the wrong object system for the problem leads to all sorts of trouble, so if you're the language designer, which to choose? Single despatch single inheritance won't deal well with 'multiple factors driving polymorphic behaviour so potentially exponentially many different behaviour combinations.'

    To synopsize, there are many ways of constructing objects, and scheme, the language discussed in SICP, just gives you a basic toolkit from which you can construct the one you need.

    In a real scheme program, you'd build your object system by hand and then hide the associated boilerplate with macros.

    In clojure you actually have a prebuilt object/dispatch system built in with multimethods, and one of its advantages over the traditional approach is that it can dispatch on the types of all arguments. You can (apparently) also use the heirarchy system to give you inheritance-like features, although I've never used it, so you should take that cum grano salis.

    But if you need something different from the object scheme chosen by the language designer, you can just make one (or several) that suits.

    That's effectively what you're proposing above.

    Build what you need, get it all working, hide the details with macros.

    The argument between FP and OO is not about whether data abstraction is bad, it's about whether the data abstraction system is the place to stuff all the separate concerns of the program.

    "I believe that a programming language should allow one to define new data types. I do not believe that a program should consist solely of definitions of new data types."

提交回复
热议问题