Since I worked, I have been using object-oriented thinking in programming. Of course, I’ve heard of functional programming, but only a little bit, never written.
Recently when nothing to look for some information, but also try to write their own ideas of functional programming code. After all, this is also a programming idea, although not as widely used as object orientation (of course, it may just be my perception, after all, I am all object oriented in use), but understanding its programming idea provides a new way to solve the problem.
Here’s a quick summary of my recent experience with functional programming.
At first, I thought that replacing the basic unit of object-oriented classes with the basic unit of functions was functional programming, but it turned out that I was still using object-oriented thinking.
So what is functional programming?
F (x)=2x. This is a function of one variable.
At the same time, nesting of functions is also used when calculating various functions, such as:
- f(x)=2x
- g(x)=x+2
- q(x)=g( f(x) )
Does this nesting of functions also apply to programming? That’s right. Take the requirement to print the odd ones digit in a list.
The traditional way to write this is as follows (PHP version):
function dispose($arr){
foreach ($arr as $item) {// Filter even numbers
if($item % 2= =0) continue;
// Retrieve the ones digit
$digit = $item % 10;
// Output the ones digit
echo 'Current number:'.$digit, PHP_EOL;
}
}
dispose([12.24.37.115]);
Copy the code
What if I wrote it in this nested form?
// Filter even numbers
function filterEvent($arr){
foreach ($arr as $item) {if($item % 2= =0) continue;
yield $item; }}// Retrieve the units digit
function getDigit($arr){
foreach ($arr as $item) {yield $item % 10; }}// Convert a number to a string
function getEchoStr($arr){
foreach ($arr as $item) {yield 'Current number:'.$item.PHP_EOL; }}// Outputs each option in the array
function echoItem($arr){
foreach ($arr as $item) {echo $item;
}
}
echoItem(
getEchoStr(
getDigit(
filterEvent([12.24.37.115))));Copy the code
The latter one is not only the call, but also can clearly see the execution process, but it looks a little ugly. It’s like a pipeline, and the data flows through the pipeline to get the final result. Wait, the pipes — they look familiar.
Linux commands use this idea. Nesting of functions can be ugly, and there is a lot of repetitive code in every method that needs to be traversed. But it would be nice to have commands like Linux’s. Don’t say, it does, but it’s implemented in Python (via operator overloading), and it’s going to look pretty when you see this implementation, because when I first wrote it, it really clicked.
class Pipe(object) :
def __init__(self, func) :
self.func = func
# this method when the bit operations | calls on the left side of the operator is not supported
def __ror__(self, other) :
for item in other:
if item is None:
continue
yield self.func(item)
@Pipe
def filter_event(item) :
return item if item % 2! =0 else None
@Pipe
def get_digit(item) :
return item % 10
@Pipe
def get_echo_str(item) :
return 'Current number:' + str(item)
@Pipe
def echo(item) :
print(item)
def pipeline(sqs) :
A null loop is required, otherwise the function will not execute
for item in sqs: pass
arr = [12.24.37.115]
pipeline(arr | filter_event | get_digit | get_echo_str | echo)
Copy the code
Does this call look like the Linux command line?
In functional programming, data is handled in one of three ways:
- Map: Transforms data, one-to-one
- Filter: Filters data
- Reduce: aggregates data
A data source, flowing through each pipeline, is processed in the above three ways to get the final result. Wait, that’s what Spark does.
In purely functional programming, functions do not store external state; for a function, certain inputs are received and certain outputs are returned. Concurrency is not a concern, and since there is no external state, it is extremely friendly for unit testing.
Given my use of functional programming, it may not be comprehensive to summarize several features of functional programming:
- Pipeline operations. you can combine simple operations into one complex operation by passing data through successive pipelines.
- Treat functions as first-class objects
- Delay processing. This is my own opinion. Since the function has no external impact, the return value of the function can be retrieved when it is actually used.
- No concurrency issues. only for pure functional programming.
Of course, I also tried to use functional programming to do something slightly more complicated, how to say. The idea of functional programming doesn’t seem to work as well for some of the more complex features, most likely because I haven’t converted to it for the most part, so it’s hard to write.
However, in some simple cases, I feel that the operation of the pipe is really beautiful.
Besides, functional programming is more than that, and this is just a brief experiment for a while