Recursive Data Structures

58 views
Skip to first unread message

andrew batutin

unread,
Dec 4, 2014, 4:36:33 PM12/4/14
to swift-l...@googlegroups.com
Hi
Swift is nice with all the functional goodies included int it.
But one thing really annoying for me. 
We can't define recursive data structures

So such code

public struct BinaryTree<T:Comparable>{


    var leftNode:BinaryTree? = nil


    var rightNode:BinaryTree? = nil


    var nodeValue:T? = nil

}

is not compilable cause of 

BinaryTree.swift:9:15: Recursive value type 'BinaryTree<T>' is not allowed
error

I've seen a way around this issue boxing the leaf value at new class. But it looks ugly.
Is there any better way?
Or can we make Apple improve compiler?


andrew batutin

unread,
Dec 4, 2014, 4:40:45 PM12/4/14
to swift-l...@googlegroups.com
Hi Andrew
You can just use class instead of struct
It's not perfect. But tolerable.

andrew batutin

unread,
Dec 4, 2014, 4:59:17 PM12/4/14
to swift-l...@googlegroups.com
And how about Empty type?
Is there smthng is Swift to represent Empty type?
Like empty leaf?


On Thursday, December 4, 2014 11:36:33 PM UTC+2, andrew batutin wrote:

Jens Alfke

unread,
Dec 4, 2014, 7:39:58 PM12/4/14
to andrew batutin, swift-l...@googlegroups.com

On Dec 4, 2014, at 1:59 PM, andrew batutin <abat...@googlemail.com> wrote:

And how about Empty type?
Is there smthng is Swift to represent Empty type?

That's what the "?" syntax is for. It denotes a reference that may be empty.

—Jens

Jeremy Pereira

unread,
Dec 5, 2014, 11:46:30 AM12/5/14
to swift-l...@googlegroups.com, andrew batutin
As I understand it, structs are value types. Trying to define a recursive struct, even using optionals is effectively defining an infinitely large object.

You wouldn't expect this to work in C would you:

struct BinaryTree
{
struct BinaryTree left;
struct BinaryTree right;
};

You need to use references, which means in Swift, you need to use a class not a struct.

class Foo<T: Comparable>
{
var left: Foo<T>?
var right: Foo<T>?
var value: T?

init(left: Foo<T>?, right: Foo<T>?, value: T?)
{
self.left = left
self.right = right
self.value = value
> --
> You received this message because you are subscribed to the Google Groups "Swift Language" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to swift-languag...@googlegroups.com.
> To post to this group, send email to swift-l...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/swift-language/03fa9f58-7d39-4033-9f54-86a633756832%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages