Dynamically Typed Languages Are Not What You Think

add x y = x + y
add(x::Int64, y::Int64) = x + y

The Haskell Case

Consider what happens if you got these two lines in Haskell

add 1 4
add 2 'c'
No instance for (Num Char) arising from a use of ‘add’
In the expression: add 2 'c'
In an equation for ‘it’: it = add 2 'c'
add :: Num a => a -> a -> a
add :: Int -> Int -> Int
add :: Int -> (Int -> Int)

The Julia Case

In a dynamic language using a just in time compiler (JIT) it is a bit harder to separate compile time and runtime. Code gets compiled to machine code on the fly while the program is running.

add(2, 'c')
ERROR: MethodError: no method matching add(::Int64, ::Char)
Closest candidates are:
add(::Int64, ::Int64) at samplecode.jl:1

Conclusion

Type information in static and dynamic languages are used different. In static languages they are used to prevent the compilation of programs containing expressions where types don’t match up. You can’t call functions with types they don’t allow.

class Dog:
def speak(self):
return "bark"
class Cat:
def speak(self):
return "meow"
>>> dog = Dog()

>>> cat = Cat()

>>> dog.speak()
'bark'

>>> cat.speak()
'meow'

>>> "animal".speak()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'speak'
'str' object has no attribute 'speak'
speak(animal::Cat) = "meow"
speak(animal::Dog) = "bark"

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Erik Engheim

Erik Engheim

11.5K Followers

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.