Hacker News new | ask | show | jobs
by StefanKarpinski 4383 days ago
> In reality "min" should just be a function, and you should write a separate function for each type you want to define it over. This is how this problem is solved in C, and almost all other languages.

This is not how it's solved in any languages with any degree of polymorphism. Of course, C is entirely devoid of polymorphism – except for its math operators like `<` and `+` – so having a version of `min` for every type you ever want to take a min of is how you're forced to do things. But no, `min` is not pathological – it's completely normal for math programming. If you look at math libraries written in monomorphic languages like C and Fortran – BLAS and LAPACK, or hell, just math.h – they are full of multiple nearly identical versions of functions that take different argument types and begin and/or end in different letters to indicate these types: `round`, `roundl`, `roundf`, etc. In LAPACK, it's completely conventional – "s" for single float, "d" for double float, "c" for single complex, "z" for double complex [1]. You'll note that the LAPACK naming scheme also encodes the type of matrix it operates on (there are 28 of them).

That's all fine, right? Well, it's fine if you're ok with writing every function four times. And that's only dealing with polymorphism in one argument. Hint: it's not at all uncommon for math functions to take multiple arguments. This is precisely why the first thing that a principled approach to mathematical programming does is allow polymorphism – ideally on multiple arguments. This is why people do math work in dynamic languages with lots of polymorphism, like Mathematica, Matlab, R and Python. Otherwise you can't get any work done without writing everything dozens of times – or struggling with C macro programming that makes this min puzzle look utterly tame. Sussman et al.'s SICM (SICP but for classical mechanics), not content with a dynamic language, immediately builds a multiple dispatch system on top of Scheme. R supports an awkward multiple dispatch system in one of its four object systems. This is why Guy Steele included multiple dispatch in Fortress. This is why Julia has multiple dispatch as its core paradigm. You need it for math. Badly.

[1] http://www.netlib.org/lapack/lug/node24.html