Function synthesis and application in Python

Recommendations for function synthesis-Introduction to functional languages dedicated to object-oriented programmers Part 1

Recommendations for applying functions-Introduction to functional languages dedicated to object-oriented programmers Part 2

I found an article like the one above, so I thought I'd like to do it in Python too ^ ~ ~, so I tried it a little.

First of all, from the implementation of the function for function synthesis (g ∘ f) (x) = g (f (x))

def compose(f_t_u, f_u_r):
    '''
    :type f_t_u: t -> u
    :type f_u_r: u -> r
    :rtype: t -> r

    >>> comp(lambda a: a + 'oppai', lambda b: b + 'hoge')('')
    'oppaihoge'
    >>> comp(comp(lambda a: a+'oppai', lambda b: b+ 'hoge'), lambda x: '[' + x + ']')('')
    '[oppaihoge]'
    '''
    return lambda t: f_u_r(f_t_u(t))

I tried to put something like a type annotation, but I'm not sure if it's easier to read.

By the way, the function composition is done above, but the parentheses are full. Scala I'm not sure, but the original article seems to use operators and implicit type conversions to get rid of parentheses. Scala scared

However, Python cannot define the oleore operator in the first place. So, here we will work on the neutralization of the function. Everyone loves __ror__, __or__ overloads and rewrites the compose.

class infix(object):
    def __init__(self, function):
        self.function = function

    def __ror__(self, other):
        self.left = other
        return self

    def __or__(self, other):
        return self.function(self.left, other)

    def __call__(self, value1, value2):
        return self.function(value1, value2)

@infix
def c(f_t_u, f_u_r): return lambda t: f_u_r(f_t_u(t))

Well, with this


(str.upper |c| sorted |c| set)('abcdeabc')
# > set(['A', 'C', 'B', 'E', 'D'])

You can now write like this.

Finally, let's implement a container called Ap that appears in Part 2 of the original article. Use the right bit shift operator to take the function and use it as appropriate.

class Ap(object):
    def __init__(self, val):
        self.val=val
    def __rshift__(self, func):
        return func(self.val)

By using this guy


Ap('abcdeabc') >> (str.upper |c| sorted |c| set)
# > set(['A', 'C', 'B', 'E', 'D'])

I can now write. I've done it.

There are still parentheses left, but it's okay to finish. I like this because it's interesting, but I don't think it's practical because I don't think it's Python-like.

# Addendum

Implementation of Ap class


class _Ap(object):
    def __rlshift__(self, other):
        self.value = other
        return self

    def __rshift__(self, other):
        return other(self.value)
Ap = _Ap()
a = Ap

If you do


'abcdacb' <<a>> (str.upper |c| sorted)
#> ['A', 'A', 'B', 'B', 'C', 'C', 'D']

It's like this. This is a visual closer to the original article, and it gives a more apply feeling (?)

Postscript:

It's less versatile, but I've also written something that looks like Haskell and has an atmosphere that allows function composition with ..

[Haskell synthesis operator. In Python ~ Implementation of Collection processing by function synthesis](https://hachibeechan.hateblo.jp/entry/implements-the-haskells-compose-function-in-python-and-list- processing)

Recommended Posts

Function synthesis and application in Python
I tried function synthesis and curry with python
Use callback function in Python
Nonlinear function modeling in Python
Draw implicit function in python
Immediate function in python (lie)
Unittest and CI in Python
Introduce pipe operators and function synthesis to Python (provisional)
Implement R's power.prop.test function in python
Difference between list () and [] in Python
Function argument type definition in python
Difference between == and is in python
python function ①
Included notation in Python function arguments
Authentication using tweepy-User authentication and application authentication (Python)
Application to display and search local memos (diary) in Python
Web application development memo in python
[Python] function
Write AWS Lambda function in Python
Manipulate files and folders in Python
Measure function execution time in Python
Assignments and changes in Python objects
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
Check and move directories in Python
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Export and output files in Python
[Python] Difference between function and method
Reverse Hiragana and Katakana in Python2.7
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
python function ②
Create and read messagepacks in Python
[Python] Function arguments * (star) and ** (double star)
[Introduction to Udemy Python3 + Application] 49. Function citation and return value declaration
File open function in Python3 (difference between open and codecs.open and speed comparison)
Overlapping regular expressions in Python and Java
Differences in authenticity between Python and JavaScript
Notes using cChardet and python3-chardet in Python 3.3.1.
Modules and packages in Python are "namespaces"
Avoid nested loops in PHP and Python
Differences between Ruby and Python in scope
AM modulation and demodulation in Python Part 2
difference between statements (statements) and expressions (expressions) in Python
Precautions when pickling a function in python
Eigenvalues and eigenvectors: Linear algebra in Python <7>
Implementation module "deque" in queue and Python
Line graphs and scale lines in python
Implement FIR filters in Python and C
Differences in syntax between Python and Java
Check and receive Serial port in Python (Port check)
OR the List in Python (zip function)
Search and play YouTube videos in Python
[Introduction to Udemy Python3 + Application] 45. enumerate function
[Introduction to Udemy Python3 + Application] 41. Input function
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Write O_SYNC file in C and Python
Dealing with "years and months" in Python
[Introduction to Udemy Python3 + Application] 46. Zip function
Read and write JSON files in Python
Easily graph data in shell and Python