title: Scala set function
body: <p>In Stanford Scala course I've come across the following assignment:</p>
  
  <p><strong>Exercise 1 – Sets as Functions:</strong></p>
  
  <p>In this exercise we will represent sets as functions from Ints to Booleans:</p>
  
  <pre><code>type Set = Int =&gt; Boolean
  </code></pre>
  
  <p><strong>a</strong>) Write a function "set" that takes an Int parameter and returns a Set containing that Int.</p>
  
  <p><strong>b</strong>) Write a function "contains" that takes a Set and an Int as parameters and returns true if the Int is in the Set and false otherwise.</p>
  
  <p><strong>c</strong>) Write the functions "union", "intersect", and "minus" that take two Sets as parameters and return a Set.</p>
  
  <p><strong>d</strong>) Can you write a function "subset" which takes two Sets as parameters and returns true if the first is a subset of the second and false otherwise?</p>
  
  <p>Solutions to the <strong>a</strong>, <strong>b</strong> and <strong>c</strong> are fairly trivial:</p>
  
  <pre><code>def set(i: Int): Set = n =&gt; n == i
  
  def contains(s: Set, i: Int) = s(i)
  
  def union(a: Set, b: Set): Set = i =&gt; a(i) || b(i)
  
  def intersect(a: Set, b: Set): Set = i =&gt; a(i) &amp;&amp; b(i)
  
  def minus(a: Set, b: Set): Set = i =&gt; a(i) &amp;&amp; !b(i)
  </code></pre>
  
  <p>But is there any elegant solution for <strong>d</strong>?
  Of course, strictly speaking, the answer to <strong>d</strong> is "yes", as I can write something like:</p>
  
  <pre><code>def subset(a: Set, b: Set) = Int.MinValue to Int.MaxValue filter(a) forall(b)
  </code></pre>
  
  <p>but that's probably not the right way.</p>