0

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.

12
  • 1
    FP in an FP language has the potential to be shorter or at least equal. Javascript isn't a dedicated FP language, so it's not very surprising that it may be slightly more cumbersome than the naturally applicable ?: operator. Also, the goal of FP isn't to be shorter. Commented Jul 5, 2019 at 11:04
  • 3
    No, with FP the code frequently gets way less verbose, because it is desriptive and at a highly generalized level. Additionally, FP doesn't mean to work with functions exclusively but with expressions rather than statements. The conditional operator is a perfectly fine expression. Commented Jul 5, 2019 at 11:05
  • 6
    I don't see how the first code line you give is not functional. It doesn't rely on side effects or mutable state. Commented Jul 5, 2019 at 11:05
  • 1
    The ?: operator is—let me count—*two* characters. It'll be very hard indeed to be any more concise then this, when a function invocation alone is already at least three characters. Commented Jul 5, 2019 at 11:35
  • 2
    @JohnColeman higher order functions like map and reduce came in ES5. ES5 was a pretty big step, much bigger than from ES5 til ES6 IMO. Commented Jul 5, 2019 at 11:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.