How to define some class (or type) of objects with methods etc. (like integer comparing) in Erlang?
How can I, for example, do this:
qsort([Pivot|T]) ->
qsort([X || X <- T, X =< Pivot])
++ [Pivot] ++
qsort([X || X <- T, X > Pivot]).
If I want to sort list of some objects, persons for example.
The very quick answer: You don't want to go there.
The longer answer: Erlang is not an object oriented language in the "traditional sense" of e.g., Java. But it has several mechanisms that might act as a stand-in for objects: First there is closures which can easily encode the equivalent of objects although the encoding is so unwieldy that it is hardly ever used. Rather people tend to "cherry-pick" and get the specific idea they need from OO be it incapsulation, inheritance, polymorphism and so on.
Second there are processes. A process is a seperate encapsulated entity to which you can send messages and receive answers. It is almost the same as "A class is a separate encapsulated entity to which you can use methods to operate on it". Since spawning a process is cheap, it is not a problem to use processes somewhat as OO-style objects.
Third there are parameterized modules which some people like to use as if they bring back OO-style code to the language.
Fourth, there are first-class functions. Since you can pass a function around as easily as data, you can often use this to generalize code rather than building an object hierarchy.
In conclusion: If you write Erlang in idiomatic style, you will rarely find the need for the equivalent of a 'class'.
You can't (at least if you want to be taken seriously as an Erlang programmer whilst having Erlang code that works properly).
Erlang is a functional programming language, not an object-oriented programming language. The whole basic concept of an "object" (a collection of state with attached functions) is anathema to the functional approach (which eschews mutable state as much as possible). You could kludge together an object-like setup in a functional language -- especially an impure one like Erlang -- but the resulting code would be hard to read, hard to maintain, fragile and ugly. (Harder to read and maintain, more fragile and uglier than even OOP code written in an OOP language, hard as that may seem to be to believe.)
You'd serve your needs far better by either:
Doing half-assed OOP in a non-OOP language is generally fruitless and painful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With