2014-10-22 55 views
0

我是Scala的新手,正在處理List和Pattern Matching上的一個小任務。賦值是直接計算列表中每個唯一字符的頻率併發出(Char,Int)元組的列表。我正在嘗試模式匹配的行上發現錯誤(...case(cs.head, _)...)以查看當前字符是否已經被計數。得到一個錯誤「構造函數不能實例化到預期類型;找到:(T1,T2)required:List [(Char,Int)]」

def times(chars: List[Char]): List[(Char, Int)] = { 
    def calcCharFreq(c: Char, cs: List[Char], count: Int): (Char, Int) = { 
     if(cs.isEmpty) (c, count) 
     else 
      if(c == cs.head) calcCharFreq(c, cs.tail, count+1) 
      else calcCharFreq(c, cs.tail, count) 
    } 

    def calcFreq(cs: List[Char], pairs: List[(Char, Int)]): List[(Char, Int)] = { 
     if(cs.isEmpty) pairs 
     else{ 
      pairs match { 
       case (cs.head, _) => calcFreq(cs.tail, pairs) 
      } 
      calcFreq(cs.tail, calcCharFreq(cs.head, cs.tail, 0) :: pairs) 
     } 
    } 
    calcFreq(chars, Nil) 
} 

在此先感謝 SK

+0

'pairs:List [(Char,Int)]'是一個List,並且您將它作爲Tuple2進行匹配。 – tuxdna 2014-10-22 10:13:22

+0

啊,Coursera課程再次開始時出現的問題。不用擔心榮譽代碼太多?另一位用戶認爲是相同的方式:http://stackoverflow.com/questions/26502978/counting-occurences-of-characters-in-a-string-using-tail-recursion – 2014-10-23 07:35:09

+0

@Paul最後我知道,你沒有義務在無論如何回覆。歡迎您坐在高臺上停止光顧。 – user4169365 2014-10-24 13:02:36

回答

1

實際檢查,看看是否已經有一個元組pairs您當前的字符(cs.head)匹配,你想要的東西,如更換包含有問題的比賽else子句:

if (pairs.exists(_._1 == cs.head)) { 
    calcFreq(cs.tail, pairs) 
    } else { 
    calcFreq(cs.tail, calcCharFreq(cs.head, cs.tail, 1) :: pairs) // I noticed this needed to pass a 1, not a 0, for the initial count, or you would fail to count the first instance of the character... 
    } 

的匹配本身不會編譯,因爲@tuxdna和@AlexeyRomanov已經給出了原因。

+0

非常感謝您的意見。有效。儘管我還不明白''_._ 1 ..'的語法,我相信在接下來的幾周內,我將能夠更多地理解這一點。再次感謝。 – user4169365 2014-10-23 01:48:47

+0

第一個下劃線表示正在檢查的當前對,第二個下劃線實際上是字段名稱「_1」的一部分,它是兩個字段對(即,鍵)的第一個字段。說比較詳細的方式是'pairs.exists(current => current._1 == cs.head)'。 – Shadowlands 2014-10-23 02:42:19

0
  1. 您不能在模式匹配這樣使用cs.head。您需要將其分配給以大寫字母開頭的變量(即使在外部範圍內存在此類標識符,小寫變量case也會創建新的變量)。 (2元素)元組的模式,pairs不是元組。要匹配列表的頭部和尾部,請編寫case head :: tail

結合,在這種情況下,你需要

else { 
    val C = cs.head 
    pairs match { case C :: _ => ... } 
} 

請注意,你需要處理其他案件。

相關問題