Custom List data structure implementing SequenceType with using of GeneratorOf struct

151 views Asked by At

My attempts to understand Generators and Sequences lead me to an idea of implementing my own list data structure and implement protocols to use forIn loop. My code:

class GSList<T> : SequenceType
{
    var Next : GSList<T>?
    var Value : T

    init(_ value: T, next : GSList<T>?)
    {
        self.Value = value
        self.Next = next
    }

    func add(list: GSList<T>)
    {
       if (self.Next != nil)
       {
            self.Next?.add(list)
       } else
       {
            self.Next = list
       }
    }

    typealias Generator = GeneratorOf<GSList<T>>

    func generate() -> Generator
    {
        var current: GSList<T>? = self
        println(current?.Value)

        return GeneratorOf
            { () -> GSList<T>? in

                let returnValue = current
                current = self.Next
                println(self.Value)
                println(current?.Value)
                return returnValue
        }
    }
}


var list1 = GSList(1, next: nil)
var list2 = GSList(2, next: nil)
var list3 = GSList(3, next: nil)
var list4 = GSList(4, next: nil)
var list5 = GSList(5, next: nil)


list1.add(list2)
list1.add(list3)
list1.add(list4)
list1.add(list5)

var generator = list1.generate()

generator.next()
generator.next()
generator.next()
generator.next()
generator.next()

It doesn't have any compile time errors but the problem is that current variable is not updated with Next value in generate() method:

func generate() -> Generator
        {
            var current: GSList<T>? = self
            println(current?.Value)

            return GeneratorOf
                { () -> GSList<T>? in

                    let returnValue = current
                    current = self.Next
                    println(self.Value)
                    println(current?.Value)
                    return returnValue
            }
        }

So calling to next generator.next() always returns first item.

How can I avoid this?

1

There are 1 answers

0
oisdk On BEST ANSWER

Your line

current = self.Next

should be

current = current?.Next