简体   繁体   English

函数式编程

[英]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): 例如,如果您有这样的代码(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. 以较少或相似的代码长度以FP样式很难做到这一点。

For example in FP pseudo library: 例如在FP伪库中:

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. 但是,您会发现它比命令式样式还要多10个字符。

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. 该代码只是示例,但我注意到在很多情况下FP样式比命令性代码更长。

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. 每种函数式编程语言都有类似的东西,包括像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(?) . 您可以调用runAdminFunction(F.if) ,但不能调用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. 函数式编程库之所以具有F.if是为了在此类情况下保持完整性,这不是因为在您的示例情况下,在三元运算符上使用F.if是一种更易读或更好的功能风格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM