Is it possible to do functional programming in a language without functions? - 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"?
I mean "functional programming" in the sense of functions as first class objects, not as in prohibiting mutable state.

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.

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.

A function (or more precisely a procedure, since we are not talking about referential transparency here) is isomorphic to an object with only a single method.
That's how first-class procedures are faked in Java, for example: with so-called SAM interfaces (Single Abstract Method). It's also how first-class procedures are "faked" in Ruby: anything which responds to call (and maybe to_proc) is a first-class procedure. There is a convenience class called Proc which provides additional features for "procedures" such as currying, and there is literal syntax (-> (x, y) { x + y }) for procedures which creates instances of the Proc class, but those two aren't strictly necessary:
def (i_am_a_first_class_procedure = Object.new).call(x) p x end
i_am_a_first_class_procedure.(42)
# 42
Scala is similar, except the method is called apply, not call. In Python, it's a "magic" method called __call__.
Note: I am ignoring closures here. Closures are procedures with state, and objects of course can have state, too, so there's not a real problem in representing them, but expressing the lexical capture of free variables in terms of an object with instance variables gets rather hairy.

Naturally yes, as long as the language is Turing complete.
Added later:
Actually, Ruby supports several cases of typical functional programming. Matz himself stated something about "providing toys for functional programming kids" when he wass adding #curry method to Proc class in Ruby 1.9 But you can do functional programming with methods as well.

Related

Is there an identity function in Ruby?

I'm currently writing a Ruby class that provides a menu of base lambdas that can be mixed-and-matched to create a new set of lambdas. (it's an evolutionary algorithm that requires a lot of customizing of the fitness function depending on the dataset)
The configuration fire where this happens it full of stuff like this
function_from_modifier.(base_function, either.(modifier_from.(case),->(x){x}) )
The identity function ->(x){x} pops up several times in the configuration file, and it looks ugly, so I was wondering if there is a more elegant way of doing this. Is something like Elixir's &(&1) possible in Ruby?
tl;dr summary: there is no identity function in the Ruby core or standard libraries. In fact, there are no functions (in the sense of pre-defined Proc instances) at all anywhere in the core or standard libraries.
First-class functions in Ruby are kind-of second-class (if that makes sense).
When Yukihiro "matz" Matsumoto first designed Ruby, he surveyed the standard libraries of other languages for uses of first-class and higher-order functions, and he found that the vast majority of uses were:
a single function argument
that is not stored, passed, or returned
that is only immediately invoked one or more times
A significant portion of higher-order functions where this is not true are control structures (e.g. if which takes a condition and two consequences), which however he wanted to model as built-in language constructs, not library functions.
Therefore, he decided to optimize Ruby for the common case that he identified, and created blocks.
Blocks are not first-class functions:
they aren't objects
you can't send messages to them
they can't be stored in variables
they can't be returned
they can't be freely passed as arguments, you can only pass at most one and only at a special place in the argument list
As a result, real (in the sense that they are actual objects) first-class functions (Procs) are in some sense second-class language features compared to blocks:
they are more expensive in memory
calling them is slower
they are more syntactically cumbersome to create
So, in essence, it is not surprising that you are running into limitations when trying to use Ruby the way you do: that's not what Ruby was designed for.
In the past, I used to carry around a helper library with constants such like this:
class Proc
Id = -> x { x }
end
But I stopped doing that. If I want to use Ruby, I use Ruby as an OO language, if I want to do fancy FP, I use Haskell or Scala or Clojure or Racket or …
There is no anonymous functions capture in ruby, because in OOP there are objects having methods defined on them, not functions.
The most similar call would be Object#itself, and while one might do method(:itself) instead of ->(x) { x }, it would not be exactly same for many reasons.
Why would not you just assign the anonymous function to the variable and use it instead, like λ = ->(x) { x } and then use λ everywhere?
Sidenote: using a bare function instead of the block in call to either looks like a bad design to me. Blocks are faster, and everywhere in the core lib ruby uses blocks in such a case.

Java: Are Instance methods Prohibited for Domain Objects in Functional Programming?

Since Functional Programming treats Data and Behavior separately, and behavior is not supposed to mutate the the state of an Instance, does FP recommend not having instance methods at all for Domain Objects? Or should I always declare all the fields final?
I am asking more in the context of Object oriented languages like Java.
Since Functional Programming treats Data and Behavior separately,
I heard that said a lot, but it is not necessarily true. Yes, syntactically they are different, but encapsulation is a thing in FP too. You don't really want your data structures exposed for the same reason you don't want it in OOP, you want to evolve it later. You want to add features, or optimize it. Once you gave direct access to the data you've essentially lost control of that data.
For example in haskell, there are modules, which are actually the data + behavior in a single unit. Normally the "constructors" of data (i.e. the direct access to "fields") are not available for outside functions. (There are exceptions as always.)
does FP recommends not having instance methods at all for Domain Objects
FP is a paradigm which says that software should be build using a (mathematical) composition of (mathematical) functions. That is essentially it. Now if you squint enough, you could call a method a function, with just one additional parameter this. Provided everything is immutable.
So I would say no, "FP" does not explicitly define syntax and it can be compatible with objects under certain conditions.
I am asking more in the context of Object oriented languages like Java.
This is where it kind-of gets hazy. Java is not well suited to do functional programming. Keep in mind, that it may have borrowed certain syntax from traditional FP languages, but that doesn't make it suitable for FP.
For example immutability, pure functions, function composition are all things that you should have to do FP, Java has none of those. I mean you can write code to "pretend", but you would be swimming against the tide.
does FP recommends not having instance methods at all for Domain Objects?
In the Domain Driven Design book, Eric Evans discusses modeling your domain with Entities, and Value Objects.
The Value Object pattern calls for immutable private data; once you initialize the value object, it does not change. In the language of Command Query Separation, we would say that the interface of a Value Object supports queries, but not commands.
So an instance method on a value object is very similar to a closure, with the immutable private state of the object playing the role of the captured variables.
Your fields should be final, but functional code and instance methods are not mutually exclusive.
Take a look at the BigDecimal class for example:
BigDecimal x = new BigDecimal(1);
BigDecimal y = new BigDecimal(2);
BigDecimal z = a.add(b);
x and y are immutable and the add method leaves them unchanged and creates a new BigDecimal.

Are Symbols in Ruby Made with Constructors or Initializers?

In the answer to this SO question Jörg W Mittag says:
There is no such thing as a constructor in Ruby.
I didn't think much of that, until I read the Wikipedia article on constructors, which states:
Immutable objects must be initialized in a constructor.
Since symbols are immutable in Ruby, how are they made? Wikipedia would seem to think they must be made with a constructor, yet Jörg says there are no constructors in Ruby.
I'm fairly new to OOP concepts and programming in general, so it possible I am missing something fairly basic, but from my perspective it there is a contradiction between these sources.
When people say
There is no such thing as a constructor in Ruby.
they mean that there is no special method type corresponding to a constructor, the way there is in C++ and Java.
In Ruby, the initialize method is, by convention, used to initialize a new object. However, it is not a special method -- it's a method just like any other method in Ruby.
Symbols are 'initialized' in some dark inside part of the ruby runtime, that you don't need to worry about.
If you make your own immutable class in ruby, it would have to be initialized in it's "constructor", which in ruby means in it's #initialize method. The initialize method may or may not technically be a constructor, but it's the method that is called when the object is instantiated, which is the point the wikipedia article is making -- since an immutable object can't be changed once created, any state has to be set when it's created, not later.
Wikipedia article calls this 'a constructor', but different languages use different terminology or exact constructs, the wikipedia article wasn't written with ruby in mind. For ruby, "place you can set state on object instantiation" is typically initialize method. (I say 'typically', because you can do all kinds of crazy things in ruby if you try). The wikipedia article is still right that if an object is truly immutable, any setting of state happens to happen on object creation, not afterwords -- that's just the meaning of 'immutable', right?
That's for immutable classes implemented by ruby source code. But good luck finding an 'initialize' method for symbols. They don't work that way. They are just provided by ruby itself, by the runtime, and we don't need to worry about the details.

Is there a meaningful difference between pass_by_reference vs pass_by_object_sharing in ruby?

Context: i argue that saying pass_by_reference when it's really pass_by_sharing is misleading
Here is the excerpt from the book "Effective Ruby" I'm arguing against
"Most objects are passed around as references and not as actual values. When these types of objects are inserted into a container the collection class is actually storing a reference to the object and not the object itself. (The notable exception to the rule is the Fixnum class whose objects are always passed by value and not by reference.)
The same is true when objects are passed as method arguments. The method will receive a reference to the object and not a new copy. This is great for efficiency but has a startling implication.
"
The 'call by value' and 'call by object sharing' terminology matches Ruby's behavior, and
the terminology is consistent with other object orientated languages that have the same
semantics.
'Call by value' and 'call by object sharing' basically mean the same thing in object orientated languages, so which one is used doesn't really matter. Someone just thought it would clarify the confusion in the terminology to add more terminology.
If 'call by reference' was implemented in Ruby though, it would be something like:
def f(byref x)
x = "CHANGED"
end
x = ""
f(x)
# X is "CHANGED"
Here, the value of x is changed. The value being which object x refers to.
Using terms 'call by reference' just creates confusion though because they mean
different things to different people. It's unnecessary in
languages like Ruby because you don't have a choice. In languages with different
calling mechanisms like C++ and C# it makes more sense to teach these terms because
they have a real effect on programs and we can come up with non hypothetical examples
of them.
When explaining parameters in Ruby, you don't need to use any of these terms though.
They're meaningless to people that don't already know the language. Just
describe the behavior itself without that terminology and avoid the baggage.
I would say if you insist on using these terms, then use 'call by value' because it's usually considered more correct. The 'Programming Ruby' book calls it 'call by value', as well as plenty of Ruby programmers. Using the term with a different meaning than its technical one isn't helpful.
You are right. Ruby is pass-by-value only. The semantics of passing and assigning in Ruby are exactly identical to those in Java. And Java is universally described (on Stack Overflow and the rest of the Internet) as pass-by-value only. Terms about languages such as pass-by-value and pass-by-reference must be consistently used across languages to be meaningful.
The thing that is often misunderstood by people who say Java, Ruby, etc. "pass objects by reference" is that "objects" are not values in these languages, and thus cannot be "passed". The value of every variable and result of every expression is a "reference", which is a pointer to an object. The expression for creating an object returns an object pointer; when you access an attribute through the dot notation, the left side takes an object pointer; when you assign one variable to another, you copy the pointer resulting in two pointers to the same object. You always deal with pointers to objects, never objects themselves.
This is made explicit in Java as the only types in Java are primitive types and reference types -- there are no "object types". So every value in Java that is not a primitive is a reference (a pointer to an object). Ruby is dynamically-typed, so variables don't have explicit types. But you can imagine a dynamically-typed language as just a statically-typed language having exactly one type; and for languages like Python and Ruby, if this type were described, it be a pointer-to-object type.
The issue ultimately boils down to a problem of definitions. People argue over things because there is no precise definition, or they each have slightly different definitions. Rather then argue over vaguely-defined things like what is the "value" of a variable, or whether named values are "variables" or "names", etc., we need to use a definition for pass-by-value and pass-by-reference that is based purely on semantics of a language structure. #fgb's answer provides a clear semantic test for pass-by-reference. In "true pass-by-reference", e.g. with & in C++ and PHP, or with ref or out in C#, simple assignment (i.e. =) to a parameter variable has the same effect as simple assignment to the passed variable in the original scope. In pass-by-value, simple assignment (i.e. =) to a parameter variable has no effect in the original scope. This is what we see in Java, Python, Ruby, and many other languages.
I dislike people coming up with new names like "pass by object sharing", when they don't understand that the semantics are covered by an existing term, pass-by-value. Adding a new term only adds more to the confusion rather than reduce it, because it does not resolve the definitions of existing terms, only adding a new term that also needs to be defined.

Is ruby a pure object oriented programming language even though it doesn't support multiple inheritance? Please Explain

Is ruby a pure object oriented programming language even though it doesn't support multiple inheritance? If so how?, please explain.
I know that to an extent substitutes the lack of multiple inheritance by allowing one to include multiple modules within a class.
Also, I'm not sure of all of the prerequisites of a pure OOP Language. From this article, they mention
a Ruby class can have only one method with a given name (if you define
a method with the same name twice, the latter method definition
prevails..
So does it mean that Ruby doesn't support Overloading methods. If so, it still can qualify as a pure OOP Lanaguage ? If so, kindly explain the reason behind this as well.
Thank you.
There are several different families of object-oriented languages. If you're thinking of multiple inheritance and method overloading, you're probably coming from a C++ mindset where these things are taken for granted. These conventions came from earlier languages that C++ is heavily influenced by.
Ruby doesn't concern itself with the type of objects, but rather the methods they're capable of responding to. This is called duck typing and is what separates Smalltalk-inspired languages like Ruby from the more formal Simula or ALGOL influenced languages like C++.
Using modules it's possible to "mix in" methods from various sources and have a sort of multiple inheritance, but strictly speaking it's not possible for a class to have more than one immediate parent class. In practice this is generally not a big deal, as inheritance is not the only way of adding methods.
Method overloading is largely irrelevant in Ruby because of duck-typing. In C++ you might have various methods for handling string, int or float types, but in Ruby you'd have one that calls to_f on whatever comes in and manipulates it accordingly. In this sense, Ruby methods are a lot more like C++ templates.
If multiple inheritance were the only "symptom" of a OOP language, then neither would Java, C#, Python, and many more be OOP languages.
What makes a language object-oriented in the first place are naturally objects. Everything is an object in ruby. The whole language is built on the concept of objects and data. Different objects can "communicate" between each other, you can encapsulate data, etc.
Take a look at this resource: Definitions for ObjectOriented.
In the first place, the problem of multiple inheritance makes sense only for an object oriented language. The very question of asking about multiple inheritance with Ruby itself proves that Ruby is an object oriented language.

Resources