Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do functional programming in a language without functions?

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"?

I mean "functional programming" in the sense of functions as first class objects, not as in prohibiting mutable state.

like image 322
Andrew Grimm Avatar asked Dec 26 '22 18:12

Andrew Grimm


2 Answers

Blocks and Procs are first-class functions. You can pass them around to methods and functions. That's how Ruby is able to support FP-ish things like map and reduce.

More generally, a method can be viewed as a function with extra associated state (its self), but methods are rarely passed around in Ruby — though they can be — so in practice they're not as important to FP-ish idioms as blocks and Procs.

like image 184
Chuck Avatar answered Dec 29 '22 07:12

Chuck


Yes. Method vs function is quite a fine distinction.

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.

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.

like image 27
Ben Avatar answered Dec 29 '22 06:12

Ben