Dynamic typing in Python gives a lot of flexibility, but also opens up possibility for run-time errors.
import numpy as np
def add(x, y):
return x + y
print add(3, 5) # prints 8
x = np.array([1, 2])
print add(x, 3) # prints [4 5]
print add("abc", 3.0) # runtime error
Static typing in C++ catches type errors at compile-time, but more cumbersome to express generic operations (need to use templates):
#include <cstdlib>
#include <iostream>
#include <valarray>
using namespace std;
template <typename T1, typename T2>
auto add(T1 const & x, T2 const & y)
-> decltype(x+y)
{
return x + y;
}
// helper for printing valarrays
template <class T>
ostream & operator<<(ostream & ostr, valarray<T> const & va)
{
ostr << "[";
if (va.size()>0) {
auto it = begin(va);
ostr << *(it++);
for (; it!=end(va); ++it)
ostr << ", " << *it;
}
ostr << "]";
return ostr;
}
int main()
{
cout << add(3, 5) << endl; // prints 8
valarray<int> x = {1, 2};
valarray<int> y = add(x, 3);
cout << y << endl; // prints [4, 5]
cout << add("abc", 3.0) << endl; // compile-time error
return EXIT_SUCCESS;
}
The following C++ version is not flexible enough as it requires the input parameters and the result to be all of the same type. As such, it won't work with the valarray example above, where we add a valarray and a number to get back a valarray.
template <typename T>
T add(T const & x, T const & y)
{
return x + y;
}