[swift-evolution] TreeLiteralConvertible

John McCall rjmccall at apple.com
Thu Apr 14 16:22:26 CDT 2016


> On Apr 14, 2016, at 2:03 PM, Milos Rankovic <milos at milos-and-slavica.net> wrote:
>> On 14 Apr 2016, at 21:36, John McCall <rjmccall at apple.com <mailto:rjmccall at apple.com>> wrote:
>> 
>> No, you just need Tree to conform to both ArrayLiteralConvertible and IntegerLiteralConvertible, and it implements the latter by building a Value out of it.
> 
> You mean this:
> 
> public enum IntTree {
> 	case Leaf(Int)
> 	case Branches([IntTree])
> }
> 
> extension IntTree : ArrayLiteralConvertible {
> 	public init(arrayLiteral elements: IntTree...) {
> 		self = .Branches(elements)
> 	}
> }
> 
> extension IntTree : IntegerLiteralConvertible {
> 	public init(integerLiteral value: IntegerLiteralType) {
> 		self = .Leaf(value)
> 	}
> }
> 
> let tree: IntTree = [[], 1, [2, 3], [[4, 5], [6, 7], [8, 9]]]
> 
>> you'll simply have to make your Tree less generic
> 
> 
> Yep, that’s the rub… With generic trees you can express yourself freely, whether you feel like:
> 
> import SpriteKit
> 
> let actionTree: Tree<SKAction> = [
> 	◊.waitForDuration(1),
> 	[
> 		◊.fadeInWithDuration(1),
> 		◊.scaleTo(1, duration: 1)
> 	],
> 	◊.playSoundFileNamed("TaDa", waitForCompletion: false)
> ]
> 
> … or:
> 
> let johnny: DictionaryTree<String, JSONValue> =
> [
> 	"name": ◊"Johnny Appleseed",
> 	"age": ◊25,
> 	"address": [
> 		"house_number": ◊21,
> 		"street": ◊"2nd Street",
> 		"city": ◊"New York"
> 	]
> ]
> 
> I’d just love to get rid of that prefix operator…

Note that all of your examples rely not just on recursion but on heterogeneous recursion, so the multiple-conformance idea doesn't work.  Fundamentally, your trees have a payload type that needs to be constructible from different kinds of literal.  It's appropriate to model that with conformance to multiple protocols.  The ability to do that conditionally based on whether another type declares a conformance is called "conditional conformance", and it's already something we're strongly considering for the future; it's just not an easy feature to actually implement.

John.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160414/e949949c/attachment.html>


More information about the swift-evolution mailing list