2013-08-03 98 views
0

我對scala和編程一般都很陌生(僅僅爲了好玩),我試圖理解尾遞歸和集合,但調試非常困難。斯卡拉尾遞歸在2個列表之間相交

我有2所列出:

val quoters = List[Map[String,List[String]]] 

val quoted = List[Map[String,List[String]]] 

例如:

val quoters = List(Map("author1"->List("1","7","8")),Map("author2"->List("2","4","6","3")),Map("author3"->List("5","2","1","3"))) 
val quoted = List(Map("author1"->List("5","6")),Map("author2"->List("5","8","1")),Map("author3"->List("4"))) 

「quoters」 引用 「引用」 和 「援引」 也引述 「quoters」。

在這個例子中,:

author1 quoted author2 with "1" and "8", 
author2 quoted author3 with "4", 
author3 quoted author1 with "5" & author2 with "5" + "1" 

我想找到的 「quoters」 說帖圈 「援引」 說帖 「quoters」 ...

輸出應該是這樣的:

val quotesCircle = List(
Map("quoter"->"author1","receiver"->"author2","quote"->"4"), 
Map("quoter"->"author2","receiver"->"author3","quote"->"2"), 
Map("quoter"->"author3","receiver"->"author1","quote"->"1") 
) 

我的問題:

1 /我想我濫用集合(這似乎太像的Json ...)

2 /我能得到交叉口只是列表列出的有:

def getintersect(q1:List[List[String]],q2:List[List[String]])={ 
for(x<-q1;r<-q2; if (x intersect r) != Nil)yield x intersect r 
} 

但與地圖列表的結構。

3 /我想這對於遞歸,但它不工作,因爲......嗯,我真的不知道:

def getintersect(q1:List[List[String]],q2:List[List[String]])= { 
    def getQuotedFromIntersect(quoteMatching:List[String],quoted:List[List[String]]):List[List[String]]={ 
    for(x<-q1;r<-q2; if (x intersect r) != Nil) 
     getQuotedFromIntersect(x intersect r,quoted) 
    } 
} 

我希望我足夠清楚:/

謝謝提前 !

Felix

回答

0

我認爲你的數據結構中有一個額外的層。我可能會使用的名稱爲「作者」,而不是「引用」,以避免混淆,因爲/加引號之間的諧音引述:

val quoters = List(
    Map("author1"->List("1","7","8")), 
    Map("author2"->List("2","4","6","3")), 
    Map("author3"->List("5","2","1","3"))) 

val authors = Map(
    "author1" -> List(5, 6), 
    "author2" -> List(5, 8, 1), 
    "author3" -> List(4)) 

有了這個地方,和一個小功能是這樣的:

def findQuoters(article: Int): List[String] = { 
    quoters.keys.toList filter { name => 
    quoters(name) contains article 
    } 
} 

然後就可以開始用誰曾引用其作者和地方,如收集和報告不同的方式嘗試:

// For each name in the 'authors' map: 
// For each article authored by this name: 
//  Find all quoters of this article 
//  Report that author 'name' has been quoted for article 'id' by 'whom'... 

for (name <- authors.keys) { 
    for (article <- authors(name)) { 
    val qq = findQuoters(article) 
    println("author %s has been quoted %d times for article %d by %s".format(
     name, qq.size, article, qq.mkString(" "))) 
    } 
} 

它打印輸出是這樣的:

author author1 has been quoted 1 times for article 5 by author3 
author author1 has been quoted 1 times for article 6 by author2 
author author2 has been quoted 1 times for article 5 by author3 
author author2 has been quoted 1 times for article 8 by author1 
author author2 has been quoted 2 times for article 1 by author1 author3 
author author3 has been quoted 1 times for article 4 by author2 

現在,想一想你正在用這些關聯數組映射什麼。您可以有效地構建圖的鄰接矩陣。你如何去查找有向圖中的所有圓?

+0

嗨Giorgos,謝謝。我被我的數據結構困住了(你的清潔程度要好得多......)是的,我應該去找一個有向圖。更簡單! – user2648879