x = [i*2 for i in range(5)] #[0, 2, 4, 6, 8]
y = [i for i in range(8) if i%2 == 0] #[0, 2, 4, 6, 8]
z = [[1],[2],[3],[4]]
w = [j for i in z for j in i] #[1,2,3,4]
t = {str(j):j*2 for j in w} #{"1":1, "2":4, "3":6, "4":8}
#reduce (note the generator (i for i in range(20))... that's a lazy list essentially)
reduce(lambda acc, x: x + acc, (i for i in range(20)), 0) #sum(0 ... 20)
#get max value from a bunch of numbers:
f = max(i for i in range(30) if 30 % 3 == 0) #max(0, 3, 9, 12, 15, 18, 21, 24, 27, 30) = 30
#basic recursion
def myreverse(x: str) -> str:
return x if len(x) <= 1 else x[-1] + myreverse(x[:-1]) #O(N) on each slice, (However x[-1] is O(1) unlike the haskell list).
#qsort haskell style
def qsort(l: List[int]) -> List[int]:
return l if len(l) <= 1 else qsort([i for i in l if i <= l[0]]) + qsort([i for i in l if i > l[0]])
Python also supports pattern matching shown here: https://www.python.org/dev/peps/pep-0636/Additionally lambda syntax, aka python anonymous first class functions HAVE to be functional.
f = lambda x: x + 1
There is no procedural concepts like variable assignment allowed in a python lambda. This is done because they wanted to force the python lambda to be properly functional and short.The type hints that python uses are also quite good with support for generics sum types and even type level programming (however your type checker needs to support it too and basically none of them do right now) You can literally assign a type to a variable in python. See: https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
I would say the main weakness in python is that the IMPLEMENTATION is not well suited for functional programming (but the syntax VERY much is). Tail slices on lists like x[1:] cost O(N) and that's the biggest issue right now imo. It makes some valid solutions on leetcode exceed the time limit because it adds and additional N complexity on every slice when the head and tail functions in haskell cost O(1)
I'm sure some library can easily provide the underlying functional primitives python needs to be faster. Actually on that note, does anyone know of a library that solves the head tail slicing problem I described above? Probably should use the python deque, but the api for that is inherently not functional.