是否可以用没有函数的语言进行函数式编程? [英] Is it possible to do functional programming in a language without functions?
问题描述
在此评论中,有人表示Ruby没有功能,只有方法。如果Ruby没有函数,是不是可以在其中进行函数式编程?或者我对术语功能感到困惑?
In this comment, it was stated that Ruby doesn't have functions, only methods. If Ruby doesn't have functions, is it not possible to do functional programming in it? Or am I confused about the term "function"?
我的意思是函数式编程,意思是作为第一类对象,而不是禁止可变状态。 / p>
I mean "functional programming" in the sense of functions as first class objects, not as in prohibiting mutable state.
推荐答案
是的。方法vs函数是一个很好的区别。
Yes. Method vs function is quite a fine distinction.
很容易将每个特定的方法实现视为一个函数;只要把它作为一个额外的参数调用该方法的对象(如果你的语言没有明确地传递它;不太熟悉Ruby)。这并不完全给你虚拟方法调用(即在运行时由对象确定所调用的特定实现的位置)。但是,将虚拟方法调用想象为调用一个只检查其第一个参数( self ,
this
,不管它是什么),并用它来确定调用哪个方法实现。使用这些约定, object.method(param1,param2)
不同于方法(object,param1,param2)
在一个简单的句法方式中。
It's easy to view each particular method implementation as a function; just have it take as an extra parameter the object on which the method was invoked (if your language doesn't pass it explicitly; not terribly familiar with Ruby). That doesn't quite give you virtual method calls (i.e. where the particular implementation called is determined by the object at runtime). But it's also very easy to imagine a virtual method call as calling a function that just inspects its first parameter (self
, this
, whatever it's called) and uses it to determine which method implementation to call. With those conventions established, object.method(param1, param2)
differs from method(object, param1, param2)
only in a trivial syntactic way.
就我个人而言,我认为上面是真相,而面向对象的语言只是提供语法糖和优化执行,因为它这是编写/执行面向对象程序的核心部分。这种类型的系统也正是你在有功能但不是真正的类/方法时如何进行面向对象的。
Personally, I view the above as "the truth", and that object-oriented languages just offer syntactic sugar and optimised execution for this because it's such a core part of writing/executing OO programs. That sort of system is also exactly how you do OO when you have functions but not true classes/methods.
它也简单地实现函数与方法,如果你认为方法不是函数。只有一个方法,没有属性的对象!这也是你如何在像Java这样的语言中进行函数式编程,它坚持一切都是对象,并且不要让方法/函数作为第一类值传递。
It's also trivially easy to implement functions with methods, if you think methods aren't functions. Just have an object with a single method and no attributes! This is also how you do functional programming in languages like Java that insist upon everything being an object and don't let you pass methods/functions as first-class values.
你所需要的需要来完成函数式编程是你可以作为第一类值传递的东西,它可以用来执行由东西的创建者确定的代码(而不是由代码使用东西),按需访问事物的代码。我无法想象 没有这种能力的编程语言。
All you need to do functional programming is things you can pass around as first-class values, which can be used to execute code determined by the creator of the "thing" (rather than determined by the code that's using the "thing"), on demand by code that has access to the "thing". I can't think of a programming language that doesn't have this capability.
这篇关于是否可以用没有函数的语言进行函数式编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!