[swift-evolution] [Proposal] Higher Kinded Types (Monads, Functors, etc.)

Matthew Johnson matthew at anandabits.com
Wed Dec 16 11:08:39 CST 2015


IMO the keys in a dictionary are not part of the contained values and therefore not part of the Functor mapping for Dictionary (obviously a map with different semantics is possible as exhibited by the standard library).  Dictionary should implement Functor by mapping over the values while preserving the keys.

A similar problem has been noted for Set.  In that case it is not possible to uphold the usual Functor laws.  IMO that points to the need for a protocol with weaker semantics than Functor.  It would preserve the essential structure without preserving the 1 to 1 projection.  There are likely a number of cases where this would make sense.  Functor could inherit from that protocol adding additional semantic requirements but no additional syntactic requirements.

Matthew

Sent from my iPad

> On Dec 16, 2015, at 8:13 AM, Al Skipp via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> let myDictionary: [String:Int] = ["test": 1]
>> var otherDictionary = myDictionary.myMap { ($0, Float($1)) }
>> // does not fail:
>> assert(otherDictionary is [String:Float])
> 
> The trouble with Dictionary is that peculiar things can happen if we can map over keys and return a Dictionary.
> 
> let dict = ["a":1, "b":2, "c":3]
> let dict2 = dict.map { ("x", $1 * 2) } // [“x”:6]
> 
> We start with a Dictionary with 3 keys and end up with a Dictionary with 1 key! As the order of the keys is unknown, we have no idea what the value of the key will be either, it might be 6, 4 or 2. 
> 
> Swift currently avoids this bedlam by returning an Array of tuples when ‘mapping’ a Dictionary. Strictly speaking this isn’t ‘map’ in the Functor sense, but then again Dictionary is a rogue that refuses to obey the Functor laws anyway.
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151216/946b7706/attachment.html>


More information about the swift-evolution mailing list