Javascript 是一种函数式编程语言吗?

发布于 2024-09-28 00:33:03 字数 122 浏览 0 评论 0原文

仅仅因为函数是一等对象、有闭包和高阶函数,Javascript 就值得被称为函数式编程语言吗?我认为它缺乏的主要内容是纯函数,而且它“感觉”不像其他函数式语言,比如 lisp(尽管这并不是它不成为函数式语言的充分理由......)

Just because functions are first class objects, there are closures, and higher order functions, does Javascript deserve to be called a Functional Programming language? The main thing I think it lacks is Pure Functions, and it doesn't 'feel' like other functional languages, like lisp (although thats not really a good reason for it not to be a functional langauge...)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

乖乖兔^ω^ 2024-10-05 00:33:03

重复我自己的回答类似的问题,

没有公认的定义
函数式编程语言。

如果您将函数式语言定义为
支持头等舱的语言
函数和 lambda,那么是的,JavaScript *是*
函数式语言。

如果您还考虑以下因素
支持不变性、代数
数据类型、模式匹配、部分
应用程序等然后不,JavaScript
*不是*一种函数式语言。

<小时>

我鼓励您阅读
关注相关博客文章(以及
下面的评论):

Repeating my own answer to a similar question,

There's no accepted definition of
functional programming language.

If you define functional language as
the language that supports first class
functions and lambdas, then yes, JavaScript *is* a
functional language.

If you also consider the factors like
support for immutability, algebraic
data types, pattern matching, partial
application etc then no, JavaScript
*is not* a functional language.


I'd encourage you to read the
following related blog posts (and also
the comments below them):

淡写薰衣草的香 2024-10-05 00:33:03

我想说它是一种多范式语言。

编辑:它是多范式的,包括功能结构。

I would say that it is a multi-paradigm language.

EDIT: It's multi-paradigm and includes functional constructs.

泪是无色的血 2024-10-05 00:33:03

如果你将“函数式编程”这个术语延伸和扭曲到哲学讨论的地步,这个问题可能会再次开放。然而,你最终会遇到一些有用的问题,比如“C++ 真的是一种编程语言吗?”

从更日常的角度来看,您的问题的答案是“否”

函数式编程意味着程序被概念化为函数的评估,而不是控制流。代码是功能的描述,没有控制流的固有概念。

JavaScript 具有控制流,并且被概念化为命令式语言。从其设计目标来看,它显然不是一种函数式语言。

if you stretch and twist the term "functional programming" to the point of philosophical discussions, this question may be open again. However, then you end up on the level of useful questions like "Is C++ really a programming language"?

The answer to your question on more daily level is "no".

Functional programming means that the program is conceptualized as a evaluation of a function, rather than a control flow. The code is a description of functions, and has no inherent concept of a control flow.

JavaScript has got a control flow and is conceptualized as a imperative language. From its design objective, it is clearly not a functional language.

把回忆走一遍 2024-10-05 00:33:03

如今,“函数式编程”语言这个术语已经被过多使用,几乎毫无用处。有两个主要含义:

  1. 具有一流的功能
    • Javascript就是这个!
  2. 基于 lambda 演算中使用的函数,重点是避免持久可变状态(通常用传递给函数的参数替换它)
    • 正如人们常说的,Javascript 根本不是这样的!

选择你的意思,然后问题就可以回答了。

The term "functional programming" language is so overloaded these days it's almost useless. There are two dominant meanings:

  1. Has first-class functions
    • Javascript is this!
  2. Is based on functions as used in the lambda calculus, with an emphasis on avoiding persistent mutable state (often replacing it with parameters passed to functions)
    • As commonly written, Javascript is not remotely this!

Pick your meaning and then the question is answerable.

著墨染雨君画夕 2024-10-05 00:33:03

我不认为函数式编程有一个具体的定义,但是人们认为“函数式编程”的很多事情都可以用 javascript 来完成。这是这篇文章中的一个很好的简短示例。

I don't think there a concrete definition of functional programming , however many of things people consider "functional programming" can be done with javascript. Here is a good brief example in this article.

失而复得 2024-10-05 00:33:03

对我来说,Javascript 既是一种命令式语言,也是一种函数式语言,您可以选择使用其中任何一种方式,甚至(egad)两种方式。或者,您可以选择使用一种范式,而不接触另一种范式。由你决定。我和你一样,认为 Javascript 不应该被称为函数式语言,因为它允许你在函数式编程范式之间徘徊。也许如果它有某种编译指示,限制您仅使用函数式编程范例,那么我认为这会很有用。但是,总而言之,我说它更像是一种命令式/过程式语言,其中加入了一些函数式编程功能。

To me, Javascript is both an imperative language and a functional language, and you can choose to use it either way, and even (egad) both ways. Or you can choose to use one paradigm and never touch the other. It's up to you. I, like you, don't think Javascript should be called a Functional Language, because it allows you to wander in and out of the functional programming paradigm. Perhaps if it had a pragma of some kind, to limit you using only functional programming paradigms, then that would be useful, I think. But, in summary, I say it's more of a imperative/procedural language with some functional programming features tossed in.

生来就爱笑 2024-10-05 00:33:03

我倾向于不认为编程语言具有一种特定的范式,但它们适合某些范式。然而,仅仅因为它们适合特定的范例并不意味着您必须使用该范例。用 C 语言编写面向对象的程序并用 ML 编写命令式程序是完全可能的。不使用某种范式来解决问题,因为该语言不是为此设计的,这只是人为地限制自己(当然,在决定特定解决方案是否是一个好的解决方案时,您仍然应该考虑语言的限制)。

I tend not to think of programming languages as having one particular paradigm, but that they lend themselves to certain paradigms. However just because they lend themselves to a particular paradigm doesn't mean you have to use that paradigm. It's quite possible to write object oriented programs in C and write imperative programs in ML. Not using a certain paradigm to solve a problem because the language isn't designed for it is just artificially limiting yourself (of course you should still take into account the limitations of a language when deciding if a particular solution will be a good solution).

不寐倦长更 2024-10-05 00:33:03

Javascript 是有道理的。这确实取决于您如何对其进行编程。如果我用面向对象的方式编码,那不是面向对象吗?因此,如果您只是以“函数式”方式编写代码,那么它就会是函数式的。我猜它是多范式语言,所以仅仅称它为一件事并不完全准确。

Javascript is to a point. It truly depends on how you go about programming it. If I code in an OO manner, would it not be OO? So if you just code things in a 'functional' manner it would be functional. I guess it is multi-paradigm language so to call it just one thing isn't entirely accurate.

情徒 2024-10-05 00:33:03

@petraszd
我稍微重写了您的代码以获得“新”for运算符:

   
   function ffor(a, b, f){
     function it(i){
       if(i > b)return
       f(i)
       it(i+1)
     }
     it(a)
   }

   print("----" + new Date()+"----")

   var funcs = []
   ffor(0, 9, function(i){
     funcs.push(function(){return i})
   })

   ffor(0, 9, function(i){
     print(funcs[i]())
   })

但我知道这种方式对于大循环有缺点......

关于 JS 中尾部递归优化的相关问题

PS 在此发布,因为在作为评论发布时存在代码格式问题

@petraszd
I rewrite your code a little to obtain a "new" for operator:

   
   function ffor(a, b, f){
     function it(i){
       if(i > b)return
       f(i)
       it(i+1)
     }
     it(a)
   }

   print("----" + new Date()+"----")

   var funcs = []
   ffor(0, 9, function(i){
     funcs.push(function(){return i})
   })

   ffor(0, 9, function(i){
     print(funcs[i]())
   })

But I know that this way has disadvantages for big loops...

Related question about tail recurtion optimization in JS

P.S. Posted here cuz have problem with code formatting while posting as comment

森林迷了鹿 2024-10-05 00:33:03

正如我们所知,函数式编程语言不允许更改或改变函数的元素(状态),但在 javascript 中,它是允许的,从这个意义上说,它不是函数式编程语言,尽管它确实将函数视为一等公民。

As we know the functional programming language doesn't allow to change or mutate the elements(state)of functions but in javascript it is allowed in that sense it is not a functional programming language, although it does treat function as first class citizens.

半步萧音过轻尘 2024-10-05 00:33:03

首先,我们必须定义函数式编程。我将其定义为原生支持规范(或至少得到广泛认可)函数式语言(如Scheme、Racket、Haskell 或Clojure)所共享的编程风格并赋予其特权的任何语言。

其他语言,如 OCaml、Elixir 和 Scala,比 JS 拥有更深入的功能支持,但仍然倾向于被认为是多范式。 功能性是一个范围。

所有这些都非常容易引发无休止的争论和挑剔,但这个定义似乎足够可靠,足以证明 JS 不是一种严肃的函数式语言,并且可能永远不会比任何其他现代的多范式语言更重要。一流的功能。

让我们选择一个特定的功能。该语言应该执行尾部调用优化,以便您可以在线性数据结构上本机编写递归函数。几乎所有 JS 的主要实现都未能提供我们期望从典型的“函数式”语言(根据上述定义)获得的这一基本功能,并且在撰写本文时还没有计划(请参阅 JavaScript 尾部调用中的函数是否经过优化? 了解详细信息)。

让我们对 TCO 进行怀疑和折腾,但 JS 仍然无法提供您所期望的“真正的”函数式语言的不变性设计目标的哪怕一丝暗示。仅仅在语言中获得 const 就花费了几十年的时间,并且默认情况下所有对象都是可变的。

由于向后兼容的原因,这些问题并不能真正得到彻底解决;事实上,将已建立的多范式语言转变为真正的函数式语言实际上是不可能的。

JS 的功能与 Python、Perl、PHP 或 Ruby 一样,它们都提供列表上的 map/filter/reduce 操作并支持一流的函数或过程。一等函数的存在为编写函数式编程风格的代码提供了足够的机会。加上蹦床和 ramda.js,乍一看似乎很有说服力。

问题是一流的函数是否足以使语言变得“函数式”。事实上,维基百科将上述所有语言都列为函数式语言,但是,该列表包括除 C 和 Go 之外的几乎所有流行的、现代的、通用的语言(包括至少一种 明确地标识为非功能性设计),所以我认为这个定义没有提供太多区分价值。

First, we have to define functional programming. I define it as any language that natively supports and privileges the style of programming shared by canonical (or at least widely agreed-upon) functional languages like Scheme, Racket, Haskell or Clojure.

Other languages, like OCaml, Elixir and Scala have much deeper functional support than JS, but still tend to be considered multi-paradigm. Functionalness is a spectrum.

All of this is very much open to endless debate and nitpicking, but this definition seems solid enough to make the case that JS isn't a serious functional language and probably never will be one any more than any other modern, multi-paradigm language with first-class functions.

Let's pick a specific feature. The language should perform tail call optimization so you can natively write recursive functions on linear data structures. Almost all major implementations of JS fail to offer this fudamental feature that we'd expect from a typical "functional" language (by the above definition) and have no plans to at the time of writing (see Are functions in JavaScript tail-call optimized? for details).

Let's give the benefit of the doubt and toss in TCO and still, JS fails to offer even a slight hint of the immutability design goal you'd expect of a "true" functional language. Just getting const in the language took decades, and all objects are mutable by default.

These problems can't really be completely resolved due to backward compatibility; it's not really possible to turn an established multi-paradigm language into a truly functional language after the fact.

JS is about as functional as, say, Python, Perl, PHP or Ruby which all offer map/filter/reduce operations on lists and support first-class functions or procedures. The existence of first-class functions offers enough of an opening to write code that is in a functional programming style. Toss in trampolines and ramda.js and it might seem convincing at a glance.

The question is whether first-class functions are sufficient to make the language "functional". In fact, Wikipedia lists all of the aforementioned as functional languages, but then, that list includes just about every popular, modern, general-purpose language other than C and Go (including at least one that explicitly identifies as not functional by design) so I don't see that this definition offers much distinguishing value.

梦毁影碎の 2024-10-05 00:33:03

有一篇有趣的论文,发展良好(纯函数,部分应用,柯里化......)并用许多简短的例子进行了说明,在这里:
https://www.freecodecamp.org/news/function-programming-in -javascript/

There is an interesting paper, well developped (pure functions, partial application, currying ...) and illustrated with many short examples, here:
https://www.freecodecamp.org/news/functional-programming-in-javascript/

弃爱 2024-10-05 00:33:03

好吧,我不会说它是函数式编程,但我说它是面向对象的,就在今天,一位朋友说他也不会把它放在那个架子上。

因此,虽然我不会这么说,但我想还有发表意见的空间。它确实具有函数式编程的经典特征,但没有其他特征。

Well, I wouldn't say it's functional programming, but then I would say it's object oriented and just today a friend said he wouldn't put it on that shelf either.

So, while I wouldn't say it is, I guess there's room for opinion. It does have classical features of functional programming, it doesn't have others.

浅笑轻吟梦一曲 2024-10-05 00:33:03

在Javascript中,你可以做这样的事情!

// Data
var fruits = [
    { name: 'apple',  price: 5 }, 
    { name: 'orange', price: 10 }, 
    { name: 'lemon',  price: 15 }
]

// Request Data from magicURL
request('magicURL')
    .then(selectKeyOf('price'))
    .then(priceMethod('sum'))
    .then((result)=>{
        console.log(result) // 30
    })

我制作了一个 github 页面来演示这个概念,您可以克隆/查看我的实现

In Javascript, you can do something like this!!

// Data
var fruits = [
    { name: 'apple',  price: 5 }, 
    { name: 'orange', price: 10 }, 
    { name: 'lemon',  price: 15 }
]

// Request Data from magicURL
request('magicURL')
    .then(selectKeyOf('price'))
    .then(priceMethod('sum'))
    .then((result)=>{
        console.log(result) // 30
    })

I have made a github page in order to demo this concept and you can clone/view my implementation

一紙繁鸢 2024-10-05 00:33:03

我真正讨厌 javascript 的地方(如果你尝试将其视为 FP 语言)是这样的:

function getTenFunctionsBad() {
  var result = [];
  for (var i = 0; i < 10; ++i) {
    result.push(function () {
      return i;
    });
  }
  return result;
}

function getTenFunctions() {
  var result = [];
  for (var i = 0; i < 10; ++i) {
    result.push((function (i) {
      return function () {
        return i;
      }
    })(i));
  }
  return result;
}

var functionsBad = getTenFunctionsBad();
var functions = getTenFunctions()
for (var i = 0; i < 10; ++i) {
  // using rhino print
  print(functionsBad[i]() + ', ' + functions[i]());
}

// Output:
//   10, 0
//   10, 1
//   10, 2
//   10, 3
//   10, 4
//   10, 5
//   10, 6
//   10, 7
//   10, 8
//   10, 9

你需要了解 JS 堆栈环境(如果这是正确的术语,我不需要)才能理解这种行为。

例如,在方案中,您无法生成这样的东西(好吧,好吧——借助底层语言的参考资料,您可以做到):

(define (make-ten-functions)
  (define (iter i)
    (cond ((> i 9) '())
          (else (cons (lambda () i) (iter (+ i 1))))))
  (iter 0))

(for-each (lambda (f)
            (display (f))
            (newline)) (make-ten-functions))

What I really hate in javascript (if You try to look at it as FP language) is this:

function getTenFunctionsBad() {
  var result = [];
  for (var i = 0; i < 10; ++i) {
    result.push(function () {
      return i;
    });
  }
  return result;
}

function getTenFunctions() {
  var result = [];
  for (var i = 0; i < 10; ++i) {
    result.push((function (i) {
      return function () {
        return i;
      }
    })(i));
  }
  return result;
}

var functionsBad = getTenFunctionsBad();
var functions = getTenFunctions()
for (var i = 0; i < 10; ++i) {
  // using rhino print
  print(functionsBad[i]() + ', ' + functions[i]());
}

// Output:
//   10, 0
//   10, 1
//   10, 2
//   10, 3
//   10, 4
//   10, 5
//   10, 6
//   10, 7
//   10, 8
//   10, 9

You need to understand JS stack environment (I don't if it is the right term) to understand such a behavior.

In scheme for example You just can't produce such thing (Ok, ok -- with the help of underlying languages' references You can make it):

(define (make-ten-functions)
  (define (iter i)
    (cond ((> i 9) '())
          (else (cons (lambda () i) (iter (+ i 1))))))
  (iter 0))

(for-each (lambda (f)
            (display (f))
            (newline)) (make-ten-functions))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文