Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Last active July 7, 2022 22:01
Show Gist options
  • Save onelharrison/34f8022fd5de072a2a4cccb0cb59f471 to your computer and use it in GitHub Desktop.
Save onelharrison/34f8022fd5de072a2a4cccb0cb59f471 to your computer and use it in GitHub Desktop.
Code snippet showing examples of what's possible with first class functions
from typing import Callable
def double(n: int) -> int:
return 2 * n
def is_even(n: int) -> bool:
return n % 2 == 0
def make_adder(n: int) -> Callable[int, int]:
def adder(m: int) -> int:
return n + m
return adder
if __name__ == "__main__":
# 1. Functions can be assigned to variables
times2 = double
print(times2(21)) # 42
# 2. Functions can be passed to other functions arguments
evens_under10 = list(filter(is_even, range(10)))
print(evens_under10) # [0, 2, 4, 6, 8]
# 3. Functions can be returned from functions
add10 = make_adder(10)
print(add10(5)) # 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment