title: Swift protocol of the map function
body: <p>I would like to create protocol of types that can be mapped over.  </p>
  
  <p>Lets say my goal is to write a operator for map.  I realize this will not compile</p>
  
  <pre><code>func &lt;^&gt; &lt;A,B,C&gt;(f: (B) -&gt; C, a: A&lt;B&gt;) -&gt; A&lt;C&gt; {
      return a.map(f)
  }
  </code></pre>
  
  <p>Now I would like to replace <code>A</code> with a protocol such that any object that has the map function can be used with this operator.</p>
  
  <p>This is not allowed but what I would like to say is </p>
  
  <pre><code>protocol Maps {
      associatedtype E
      func map&lt;T&gt;(f: (E) -&gt; T) -&gt; Self&lt;T&gt;
  }
  </code></pre>
  
  <p>The closest I can get to something that makes sense is as follows.  However it does not work correctly. </p>
  
  <pre><code>protocol Maps {
      associatedtype E
      func map&lt;T, U: Maps&gt;(f: (E) throws -&gt; T) rethrows -&gt; U where U.E == T
  }
  
  
  extension Array: Maps {
      func map&lt;T, U&gt;(f: (E) throws -&gt; T) rethrows -&gt; U where U : Maps, U.E == T {
          return try self.map(transform)
      }
  }
  
  func &lt;^&gt; &lt;A,B,C,D&gt;(f: (B) -&gt; C, a: A) -&gt; D where A: Maps, D: Maps, A.E == B, D.E == C {
      return a.map(f)
  }
  </code></pre>
  
  <p>The main problem here being is that the map function does not return an <code>Array&lt;T&gt;</code> but a <code>Maps</code> protocol where <code>E</code> is <code>T</code>.</p>
  
  <p>Should I just break down and write a <code>&lt;^&gt;</code> operator for every custom struct that can be mapped over?  Any suggestions will be appreciated!  Thanks</p>