2013-05-10 178 views
1
def combinations(occurrences: List[(Char,Int)]): List[List[(Char,Int)]] = occurrences match { 
    case Nil => Nil 
    case x :: xs => for(z <- combinations(xs); y <- occ(x)) yield (y :: z) 
} 

def occ(e: (Char, Int)): List[(Char, Int)] = (for(i <- 0 to e._2) yield (e._1, i)).toList 

喜用的理解,在斯卡拉

我無法找到在上面的代碼中的任何瑕疵,但它仍然給了我清單()進行任何輸入。

回答

2

你是第一個用於解析會一直在你遞歸的終點,這將迫使你的遞歸的其餘部分是Nil產生Nil。這裏是一個可行的稍作修改的版本,雖然它給人的List[(Char, Int)]代替List[List[(Char, Int)]]

def combinations(occurrences: List[(Char,Int)]): List[(Char,Int)] = occurrences match { 
    case Nil => Nil 
    case x :: xs => (for { z <- combinations(xs) } yield z) ::: occ(x) 
} 

如果您的理解返回Nil的第一部分,那麼它不會評價它的其餘部分,並只返回Nil。我已經改變了一些,所以現在即使它的評估結果爲Nil,它也會與occ的結果相結合。

+0

感謝諾亞的提示! – arpanchaudhury 2013-05-10 21:17:13

0
def combinations(occurrences: List[(Char,Int)]): List[List[(Char,Int)]] = occurrences match { 
    case Nil => List(List()) 
    case x :: xs => for(z <- combinations(xs); y <- occ(x)) yield (y :: z) 
} 

def occ(e: (Char, Int)): List[(Char, Int)] = (for(i <- 0 to e._2) yield (e._1, i)).toList 

這已解決了我的問題!

7

嗯,我認爲你很接近答案。最重要的是在無爲的情況下考慮什麼是正確的回報值。

def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match { 
    case Nil => List(List()) 
    case x :: xs => 
     for { 
     z <- combinations(xs) 
     n <- 0 to x._2 
     } yield (if (n == 0) z else (x._1, n) :: z) 
    } 
+1

你也可以分解''''x'''來提高可讀性。只需將'''case x :: xs =>''替換爲'''case(char,times):: xs =>''' – 2017-03-27 02:44:21