How to use polymorphism in functional programming (with dynamic type system)?
Let’s consider following example (first in OOP second in FP). The program is very simple – there are list of figures and we need to draw all of them, different figures use different drawing algorithms.
In OOP it can be done trivially, but how to do it in FP? Especially in languages with dynamic type system, like Scheme, Clojure (without static type resolving at compile time)?
I created simple code ( live version http://tinkerbin.com/0C3y8D9Z , press ‘Run’ button ). I used if/else switch in FP sample, but it’s a very bad approach. How such problem can be solved better?
Samples are in JavaScript, but it’s only for purpose of simplicity, it would be interesting to see a solution in any functional language with dynamic typing system.
OOP
var print = function(message){document.write(message + "\n<br/>")}
// Object Oriented Approach.
var circle = {
draw: function(){print("drawing circle ...")}
}
var rectangle = {
draw: function(){print("drawing rectangle ...")}
}
var objects = [circle, rectangle]
objects.forEach(function(o){
o.draw()
})
FP
var print = function(message){document.write(message + "\n<br/>")}
// Functional Approach.
var circle = {type: 'Circle'}
var drawCircle = function(){print("drawing circle ...")}
var rectangle = {type: 'Rectangle'}
var drawRectangle = function(){print("drawing rectangle ...")}
var objects = [circle, rectangle]
objects.forEach(function(o){
if(o.type == 'Circle') drawCircle(o)
else if(o.type == 'Rectangle') drawRectangle(o)
else throw new Error('unknown type!')
})
OO polymorphism is not a part of functional programming. However some functional languages (e.g. clojure) have oo polymorphism.
Another kind of polymorphism is multimethods
Or you just can use functional style