user2693928
user2693928

Reputation:

Functional programming If

I like functional programming concepts but I think that much of the time the code becomes larger and messier.

For example if you have code like that (JS):

let str = user.status == 'is_admin' ? 'active user' : 'user inactive';

It's very hard to do this in FP style with less or similar code length.

For example in FP pseudo library:

let str = F.if(F.propEq('status', 'is_admin'), 'active user', 'user inactive'))(user)

But you see its ~10 chars more than the imperative style.

Do you have suggestions if it can be shortened?

The code is just sample but I noticed in many cases the FP style gets longer than the imperative code.

Upvotes: 0

Views: 130

Answers (1)

Karl Bielefeldt
Karl Bielefeldt

Reputation: 49128

The ternary operator is functional programming style. It's not merely an imperative statement, it's an expression. It returns a result value and doesn't rely on side effects in order to work. Every functional programming language has something similar, including the "ultra pure" ones like Haskell.

The only functional style thing you can't do with the ternary operator is pass it into or return it from a higher-order function. Say for some bizarre reason, you had a higher-order function like:

function runAdminFunction(f) {
  return f(is_admin, 'active user', 'user inactive');
}

You can call runAdminFunction(F.if), but you can't call runAdminFunction(?). Functional programming libraries have F.if for the sake of completeness in situations like these, not because it is considered more readable or better functional style to use it over a ternary operator in situations like your example.

Upvotes: 3

Related Questions