3 ms·
For readability, it's nice to have the base case at the top. For performance (if performance is an issue) it's nice to have the base case at the bottom since a
by seiji 13y ago
For readability, it's nice to have the base case at the top. For performance (if performance is an issue) it's nice to have the base case at the bottom since all function heads are evaluated in order.
If you're looping over a million element list and your base case is first, it'll be checked a million times. If your base case is last, it'll only be checked once when your normal cases no longer match.
And to clear up your confusion, the writeup is wrong about empty lists matching on [H|T]:
Eshell V5.10.1 (abort with ^G)
1> [H|T] = [1, 2, 3, 4, 5].
[1,2,3,4,5]
2> [H2|T2] = [].
** exception error: no match of right hand side value []
- mononcqc 13y agoThe BEAM virtual machine is able to reorder most clauses based on need, and for most cases, a binary search will be done through all clauses. Exceptions include function clauses with guards, which cannot easily be reordered but still impact whether a clause will be used or not. The VM will instead try to reorder the clauses up until the next guard clause, if possible. You should mostly care about writing readable code and let the compiler and the VM do the rest.