Advertisement
Guest User

Untitled

a guest
May 29th, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.21 KB | None | 0 0
  1. package funsets
  2. import scala.collection.immutable.Set
  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 = Set(elem)
  23.  
  24.  
  25.   /**
  26.    * Returns the union of the two given sets,
  27.    * the sets of all elements that are in either `s` or `t`.
  28.    */
  29.     def union(s: Set, t: Set): Set = (i) => s(i) || t(i)
  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 = (i) => s(i) && t(i)
  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 = (i) => s(i) && !t(i)
  41.  
  42.   /**
  43.    * Returns the subset of `s` for which `p` holds.
  44.    */
  45.     def filter(s: Set, p: Int => Boolean): Set = intersect(s,p)
  46.  
  47.  
  48.   /**
  49.    * The bounds for `forall` and `exists` are +/- 1000.
  50.    */
  51.   val bound = 1000
  52.  
  53.   /**
  54.    * Returns whether all bounded integers within `s` satisfy `p`.
  55.    */
  56.     def forall(s: Set, p: Int => Boolean): Boolean = {
  57.     def iter(a: Int): Boolean = {
  58.       if (contains(diff(s,p), a)) false
  59.       else if (a == 1000) true
  60.       else iter(a + 1)
  61.     }
  62.     iter(-1000)
  63.   }
  64.  
  65.   /**
  66.    * Returns whether there exists a bounded integer within `s`
  67.    * that satisfies `p`.
  68.    */
  69.     def exists(s: Set, p: Int => Boolean): Boolean = {
  70.     forall(s,p)
  71.   }
  72.  
  73.   /**
  74.    * Returns a set transformed by applying `f` to each element of `s`.
  75.    */
  76.     def map(s: Set, f: Int => Int): Set = (i) => exists(s,(x) => f(x) == i)
  77.  
  78.   /**
  79.    * Displays the contents of a set
  80.    */
  81.   def toString(s: Set): String = {
  82.     val xs = for (i <- -bound to bound if contains(s, i)) yield i
  83.     xs.mkString("{", ",", "}")
  84.   }
  85.  
  86.   /**
  87.    * Prints the contents of a set on the console.
  88.    */
  89.   def printSet(s: Set) {
  90.     println(toString(s))
  91.   }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement