Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Module with functions that demonstrate closures and currying.
- """
- def uppercase_my_str(s, n):
- if n == 0:
- return s[0].upper() + s[1:]
- return s[:n] + s[n].upper() + s[n + 1:]
- # curried form
- def uppercase_at(n):
- def uppercase_my_str(s):
- if n == 0:
- return s[0].upper() + s[1:]
- return s[:n] + s[n].upper() + s[n + 1 :]
- return uppercase_my_str
- ys = ["hello", "world"]
- # returns a closure in which n = 0 (so uppers first letter)
- upper_at_1st_letter = uppercase_at(0)
- print(list(map(upper_at_1st_letter, ys)))
- # shorter notation
- print(list(map(uppercase_at(0), ys)))
- # using lambda
- print(list(map(lambda s: uppercase_at(0)(s), ys)))
Add Comment
Please, Sign In to add comment