r/functionalprogramming • u/MisturDee • May 29 '24
Question What is this called?
Hey guys!! My first time here! I am not a hardcore functional programmer, but lately I've been experimenting with the idea of using functions to represent a value that depends on another value. Although this might already be what a function means to you functional bros but it's still a new and exciting idea to me.
Say I need to conditionally display a text that has multiple translations stored in some resource files in the following code example:
import translate from '~/translate';
function getText(status) {
switch (status) {
case 'ready':
return translate => translate('status-ready');
case 'loading':
return _ => '';
case 'error':
return translate => translate('status-error');
}
}
getText('ready')(translate)
In this case the returned text depends on a resource and therefore a function of resource (translate) is returned. Instead of putting the responsibility of translating inside the function, it's delegated to the caller. It feels pretty logical to me.
Is this like a thing? Is there a name for this? Like using function as an abstract value. And is there any advantage to doing this instead of doing the above?
function getText(status, translate) {
...
}
View all comments
Show parent comment
1
u/MisturDee May 30 '24
That's some fascinating stuff. I just learned from another comment that through curry my function is actually just equivalent to having two args in my function.
However is it really currying/partial application that I am doing? I think dependency inversion is closer to what I really mean. I am doing this because I want an abstract text, an untranslated text, a black box containing some text that cannot be deciphered until it is given a translation. I could've modeled with an object or something else, but instead I did it with a function. And I am curious if it is common for functional people to represent an abstract value with a function.