Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. package funsets
  2.  
  3.  
  4. /**
  5. * 2. Purely Functional Sets.
  6. */
  7. object FunSets {
  8. /**
  9. * We represent a set by its characteristic function, i.e.
  10. * its `contains` predicate.
  11. */
  12. type Set = Int => Boolean
  13.  
  14. /**
  15. * Indicates whether a set contains a given element.
  16. */
  17. def contains(s: Set, elem: Int): Boolean = s(elem)
  18.  
  19. /**
  20. * Returns the set of the one given element.
  21. */
  22. def singletonSet(elem: Int): Set = (x: Int) => x == elem
  23.  
  24. /**
  25. * Returns the union of the two given sets,
  26. * the sets of all elements that are in either `s` or `t`.
  27. */
  28. def union(s: Set, t: Set): Set = (x: Int) => s(x) || t(x)
  29.  
  30. /**
  31. * Returns the intersection of the two given sets,
  32. * the set of all elements that are both in `s` and `t`.
  33. */
  34. def intersect(s: Set, t: Set): Set = (x: Int) => s(x) && t(x)
  35.  
  36. /**
  37. * Returns the difference of the two given sets,
  38. * the set of all elements of `s` that are not in `t`.
  39. */
  40. def diff(s: Set, t: Set): Set = (x: Int) => s(x) && !t(x)
  41.  
  42. /**
  43. * Returns the subset of `s` for which `p` holds.
  44. */
  45. def filter(s: Set, p: Int => Boolean): Set = (x: Int) => s(x) && p(x)
  46.  
  47. /**
  48. * The bounds for `forall` and `exists` are +/- 1000.
  49. */
  50. val bound = 1000
  51.  
  52. /**
  53. * Returns whether all bounded integers within `s` satisfy `p`.
  54. */
  55. def forall(s: Set, p: Int => Boolean): Boolean = {
  56. def iter(a: Int): Boolean = {
  57. if (a == bound + 1) true
  58. else if (s(a) && !p(a)) false
  59. else iter(bound + 1)
  60. }
  61. iter(-bound)
  62. }
  63.  
  64. /**
  65. * Returns whether there exists a bounded integer within `s`
  66. * that satisfies `p`.
  67. */
  68. def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, (x: Int) => !p(x))
  69.  
  70. /**
  71. * Returns a set transformed by applying `f` to each element of `s`.
  72. */
  73. def map(s: Set, f: Int => Int): Set = (x: Int) => if s(x) s(f(x))
  74.  
  75. /**
  76. * Displays the contents of a set
  77. */
  78. def toString(s: Set): String = {
  79. val xs = for (i <- -bound to bound if contains(s, i)) yield i
  80. xs.mkString("{", ",", "}")
  81. }
  82.  
  83. /**
  84. * Prints the contents of a set on the console.
  85. */
  86. def printSet(s: Set) {
  87. println(toString(s))
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement