#!/usr/bin/python3 # -*- coding: utf-8 -*- # %% Lambda functions """ These are tiny instantly executable functions, that are often defined in-place, as arguments to other functions. General format lambda argumentss: expression on arguments It must be one expression (line) It can't do arg type-hints in the function def itself, but can type-hint a the variable itself that stores a lambda. However, you usually wouldn't do that anyway... """ from typing import Callable # This is equivalent to below def add_one(x: int) -> int: return x + 1 print(add_one(2)) # to this plus_one: Callable[[int], int] = lambda x: x + 1 print(plus_one(2)) # and to this instantly evaluated lamda print((lambda x: x + 1)(2)) # This second function is equivalent to below def xplusyadd_one(x: int, y: int) -> int: return x + y + 1 print(xplusyadd_one(2, 2)) # to this xplusyplus_one: Callable[[int, int], int] = lambda x, y: x + y + 1 print(xplusyplus_one(2, 2)) # and to this print((lambda x, y: x + y + 1)(2, 2)) # Some more examples called upon definition: print((lambda x: x > 2)(3)) # => True print((lambda x, y: x ** 2 + y ** 2)(2, 1)) # => 5 # %% Lambda sum example mysum: Callable[[int, int], int] = lambda arg1, arg2: arg1 + arg2 # Now you can call sum as a function print("Value of total: ", mysum(10, 20)) print("Value of total: ", mysum(20, 20)) print((lambda: print("can have zero args"))()) # ++++++++++++ Cahoot-20.1 # https://mst.instructure.com/courses/58101/quizzes/57315