Referenced article: Comments on [JavaScript, VB.Net, Python3, Common Lisp, Clojure, HSP, R language] to suppress side effects and substitutions with Fizz Buzz problem / 543eed9386103ec9c58c # comment-7f730579d0e5e1267525) One liner in Python: recursion You don't have to make a complicated Y combinator, you just need the function to have an argument to receive itself.
I thought I couldn't write recursion in lambda (unless I did something special), but I can. I did not know that. No, I think I used to go through my brain because I couldn't understand it even if I read it.
I wrote the factorial myself by referring to the article.
do = pack_to_tuple = lambda *x : x
case = unpack_and_evaluate_in_order_then_return_last = lambda x : x[-1]
otherwise = True
f = ( lambda x :
case( x == 0 and do( 1 )
or otherwise and do( x * f( x - 1 ) )
)
)
f2 = ( lambda x :
( lambda f : f( f, x ) ) ( lambda f, x :
case( x == 0 and do( 1 )
or otherwise and do( x * f(f, x - 1 ) )
)
)
)
print(f(10), f2(10))
python
#result
3628800 3628800
It does the same thing as the upper function `f``` and the lower function
f2
``.
The upper one is recurring normally. I usually do this and understand.
What about the bottom? It's a little difficult ...
Do you feel like you're creating a function that returns factorials with anonymous recursion and naming it f2?
In the argument f of an anonymous function that takes + x and f as arguments and returns f (f, x), Pass an anonymous function that takes + f and x as arguments and returns 1 or x * f (f, x-1) depending on the value of x Anonymous function with + x as an argument
I don't know what it is ... but it can be mechanically converted from top to bottom, so it's quite so when you need it.
Please comment if it's different or something like this.
Reference article: [Python] Recursion with lambda
With keyword arguments ...
python
f3 = ( lambda x, f = lambda f, x : case( x == 0 and do( 1 )
or otherwise and do( x * f(f, x - 1 ) )
)
: f( f, x )
)
Clean. Somehow the meaning is easy to understand. I learned a lot.
Recommended Posts