Skip to content

polymorphism

pannous edited this page Mar 18, 2024 · 5 revisions

The ability to write code that can operate on different types is called polymorphism.

In dynamic languages you often find beasts such as:

function foo(x)
    if x is Integer
        x + x
    elif x is Float
        x / 2.0
    elif x is String
        length(x)
    else
        1
    end
end

This is clearly unidiomatic and should be written as

foo of int = it + it
foo of float = it / 2.0
foo of string = its length
foo of any = 1 

This kind of overloading / polymorphism is called multiple dispatch if more arguments are involved. Unlike in object orientated languages multiple dispatch functions can "belong" to multiple objects.

For example a generic function slice fruit with tool {...} would live outside the fruit and tool classes and be applicable to both.

One big disadvantage of the functional approach, besides discoverability, is lack of encapsulation and private access. This can be alleviated with modules (in case of Julia)

return type polymorphism

Thanks to return polymorphism, the concepts of arguments, functions and their return type become unified in a general matching framework:

to render text as pdf:
 return createPdf(text)

to render text as docx:
 return createDocx(text)

render "hello" as pdf
type of result == pdf

docx example = render "hello MS"

render "now what"   # error or interactive compiler question: 
# 1. render text as docx or 
# 2. render text as pdf

Again using types as parameter names. PS: the return statement here is superfluous and just for clarification purposes.

Home

Philosophy

data & code blocks

features

inventions

evaluation

keywords

iteration

tasks

examples

todo : bad ideas and open questions

⚠️ specification and progress are out of sync

Clone this wiki locally