Pure Function Question

Started by
2 comments, last by GameCreator 2 years, 10 months ago

I'm trying to understand pure functions and was wondering if this would qualify. As an example, pretend you have a code like this:

Player.DistanceToEnemy = DistanceBetween(player, enemy);
Enemy.DistanceToPlayer = DistanceBetween(player, enemy);

Is my understanding correct that the DistanceBetween function can not be a pure function because the player and enemy positions change over time, even if it's in another part of the code?

Advertisement

The only requirement for a pure function is that it always gives a consistent result for the same inputs. What's tripping you up here is that player and enemy have nested state (their respective positions), so even though you are passing the same object references in each time, you aren't passing in the same total input state.

Keep in mind that this entire concept comes from functional programming, which often don't have objects, encapsulation, or even mutable data. As a result, applying functional concepts to mainstream languages requires some interpretation.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Thank you.

This topic is closed to new replies.

Advertisement