Today I Learned - Rocky Kev

TIL the problem with using Loops

POSTED ON:

TAGS:

Loops tend to have some flaws.

Loops include

What is the problem with Loops:

Off by one error

An off-by-one error is when you expect something to be of value N, but in reality it ends up being N-1 or N+1.

For example, you were expecting the program to perform an operation 10 times, but it ends up performing 9 or 11 times (one too few or one too many times).

More details in this post

Infinite Loops

For loops, with a wrong typo, can keep going without stopping.

Statefulness

Loops keep state.

More details in this post

Hidden Intent

Loops can obscure what it was designed to do.

Alternatives to Loops

Recusion

To solve off by one errors and statefulness, you can use recusion.

BUT both loops and recursions do a poor job of signalling intent.

More details in this post

Higher Order Functions

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. The term comes from mathematics, where the distinction between functions and other values is taken more seriously. Higher-order functions allow us to abstract over actions, not just values. They come in several forms.

Higher-order functions like Map, filter, fold and friends package up common recursive patterns into library functions that are easier to use than direct recursion and signal intent.

More details in this post

More advanced methods (and way outside of my knowledge level) are these methods.

Corecusion

Transducers

Monoids

F-Algebras

REFERENCES:
https://github.com/you-dont-need/You-Dont-Need-Loops
https://thenewstack.io/4-reasons-not-to-use-programming-loops-and-a-few-ways-to-avoid-them/


Related TILs

Tagged:

TIL math module in SASS!

math in Sass, oh my!

TIL the Quake 3 Fast Inverse Square Root hack

Quake III Arena, a first-person shooter video game, was released in 1999 by id Software and used the algorithm.

TIL that the max size of a Map/Set is 26843544

JS Maps and Sets are implemented by OrderedHashTable. OrderedHashTables double in size when they need to grow, and their max size is 26843544. After 16777216 elements, doubling that exceeds the max, so the allocation fails.Currently these data structures are not implemented to be usable for large in-memory datasets. Also note that the JS specification itself doesn't require that Maps and Sets must scale with available memory.