Guest User

Untitled

a guest
Jul 18th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. """
  2. Module with functions that demonstrate closures and currying.
  3.  
  4. """
  5.  
  6.  
  7. def uppercase_my_str(s, n):
  8. if n == 0:
  9. return s[0].upper() + s[1:]
  10.  
  11. return s[:n] + s[n].upper() + s[n + 1:]
  12.  
  13.  
  14. # curried form
  15. def uppercase_at(n):
  16. def uppercase_my_str(s):
  17. if n == 0:
  18. return s[0].upper() + s[1:]
  19.  
  20. return s[:n] + s[n].upper() + s[n + 1 :]
  21.  
  22. return uppercase_my_str
  23.  
  24.  
  25. ys = ["hello", "world"]
  26.  
  27. # returns a closure in which n = 0 (so uppers first letter)
  28. upper_at_1st_letter = uppercase_at(0)
  29. print(list(map(upper_at_1st_letter, ys)))
  30.  
  31. # shorter notation
  32. print(list(map(uppercase_at(0), ys)))
  33.  
  34. # using lambda
  35. print(list(map(lambda s: uppercase_at(0)(s), ys)))
Add Comment
Please, Sign In to add comment