递归解析CollectionType [英] Recursively parse a CollectionType

查看:78
本文介绍了递归解析CollectionType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个递归下降解析器.我希望我的解析器可以处理UInt8的任何(或至少很多")集合(例如,不仅是Swift.Array)

I'm writing a recursive descent parser. I'd like my parser to work on any (or at least "many") Collections of UInt8 (e.g., not only Swift.Array)

func unpack<T: CollectionType where T.Generator.Element == UInt8>(t: T) {
    let m = t.dropFirst()
    //[do actual parsing here]
    unpack(m)
}

但是:

error: cannot invoke 'unpack' with an argument list of type '(T.SubSequence)'
note: expected an argument list of type '(T)'

这令人困惑,因为:

  1. dropFirst返回Self.SubSequence
  2. CollectionType.SubSequenceSubSequence : Indexable, SequenceType = Slice<Self>
  3. SliceCollectionType.
  4. 因此,m应该是CollectionType.
  1. dropFirst returns Self.SubSequence
  2. CollectionType.SubSequence is SubSequence : Indexable, SequenceType = Slice<Self>
  3. Slice is CollectionType.
  4. Therefore, m should be CollectionType.

但是由于某些原因,这是行不通的.如何定义unpack以便可以递归传递子序列?

However for some reason, this doesn't work. How do I define unpack so it can be recursively passed subsequences?

推荐答案

Swift中不再有CollectionType了. ArrayArraySlice都采用 Sequence .在Sequence中声明您使用的dropFirst()方法.因此,您可以像这样制作递归泛型函数:

There is no CollectionType in Swift anymore. Both Array and ArraySlice adopt Sequence. And the dropFirst() method which you use is declared in Sequence. So you can make recursive generic function like this:

func unpack<T: Sequence>(t: T) where T.Element == UInt8 {
    let m = t.dropFirst()
    //[do actual parsing here]
    unpack(m)
}

这篇关于递归解析CollectionType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆