Understanding of use

I learn a little functional programming and look at toolz. The differences between compose, pipe, thread_first and thread_last seem very subtle or nonexistent to me. What are the suggested uses for these features?

+4
source share
1 answer
  • composevs. thread_*andpipe

    composeis essentially a function linker (∘). The main goal is to combine various functions into reusable blocks . The order of applications is reversed in the order of arguments, so compose(f, g, h)(x)is f(g(h(x)))(just like (f ∘ g) (x) is f (g (x))).

    thread_* pipe . , . , , pipe(x, f, g, h) - h(g(f(x))).

  • compose vs thread_*.

    compose , thread_*. currying compose .

    , thread_ , :

    thread_last(
        range(10),
        (map, lambda x: x + 1),
        (filter, lambda x: x % 2 == 0)
    )
    

    compose :

    pipe(
        range(10), 
        lambda xs: map(lambda x: x + 1, xs), 
        lambda xs: filter(lambda x: x % 2 == 0, xs)
    )
    

    from toolz import curried
    
    pipe(
        range(10), 
        curried.map(lambda x: x + 1), 
        curried.filter(lambda x: x % 2 == 0)
    )
    
  • thread_first vs. thread_last.

    thread_first piped .

    thread_last piped .

    >>> from operator import pow
    >>> thread_last(3, (pow, 2))   # pow(2, 3)
    8
    >>> thread_first(3, (pow, 2))  # pow(3, 2)
    9
    

( ) , functools.partial/toolz.curry lambda, .

, , map functools.reduce, thread_last . , compose(h, g, f), def fgh(x) pipe(x, f, g, h). .

+4

Source: https://habr.com/ru/post/1677813/


All Articles