You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.4 KiB

  1. """
  2. A collection of functional utilities/helpers
  3. """
  4. from functools import reduce
  5. from copy import deepcopy
  6. from itertools import chain, dropwhile
  7. def getin(m, path, default=None):
  8. """returns the value in a nested dict"""
  9. keynotfound = ':com.gooey-project/not-found'
  10. result = reduce(lambda acc, val: acc.get(val, {keynotfound: None}), path, m)
  11. # falsey values like 0 would incorrectly trigger the default to be returned
  12. # so the keynotfound val is used to signify a miss vs just a falesy val
  13. if isinstance(result, dict) and keynotfound in result:
  14. return default
  15. return result
  16. def assoc(m, key, val):
  17. """Copy-on-write associates a value in a dict"""
  18. cpy = deepcopy(m)
  19. cpy[key] = val
  20. return cpy
  21. def associn(m, path, value):
  22. """ Copy-on-write associates a value in a nested dict """
  23. def assoc_recursively(m, path, value):
  24. if not path:
  25. return value
  26. p = path[0]
  27. return assoc(m, p, assoc_recursively(m.get(p,{}), path[1:], value))
  28. return assoc_recursively(m, path, value)
  29. def merge(*maps):
  30. """Merge all maps left to right"""
  31. copies = map(deepcopy, maps)
  32. return reduce(lambda acc, val: acc.update(val) or acc, copies)
  33. def flatmap(f, coll):
  34. """Applies concat to the result of applying f to colls"""
  35. return list(chain(*map(f, coll)))
  36. def indexunique(f, coll):
  37. """Build a map from the collection keyed off of f
  38. e.g.
  39. [{id:1,..}, {id:2, ...}] => {1: {id:1,...}, 2: {id:2,...}}
  40. Note: duplicates, if present, are overwritten
  41. """
  42. return zipmap(map(f, coll), coll)
  43. def findfirst(f, coll):
  44. """Return first occurrence matching f, otherwise None"""
  45. result = list(dropwhile(f, coll))
  46. return result[0] if result else None
  47. def zipmap(keys, vals):
  48. """Return a map from keys to values"""
  49. return dict(zip(keys, vals))
  50. def compact(coll):
  51. """Returns a new list with all falsy values removed"""
  52. return list(filter(None, coll))
  53. def ifPresent(f):
  54. """Execute f only if value is present and not None"""
  55. def inner(value):
  56. if value:
  57. return f(value)
  58. else:
  59. return True
  60. return inner
  61. def identity(x):
  62. """Identity function always returns the supplied argument"""
  63. return x
  64. def unit(val):
  65. return val
  66. def bind(val, f):
  67. return f(val) if val else None