私はこれが別の初心者の質問だと思います。
私がやりたいのは、単語が詩に現れる頻度を数えるためにaを使用し、そのMap
結果をコンソールに出力することです。私は(おそらくあまり慣用的ではないが)機能していると信じている次のコードに行きました:
val poe_m="""Once upon a midnight dreary, while I pondered weak and weary,
|Over many a quaint and curious volume of forgotten lore,
|While I nodded, nearly napping, suddenly there came a tapping,
|As of some one gently rapping, rapping at my chamber door.
|`'Tis some visitor,' I muttered, `tapping at my chamber door -
|Only this, and nothing more.'"""
val separators=Array(' ',',','.','-','\n','\'','`')
var words=new collection.immutable.HashMap[String,Int]
for(word<-poe_m.stripMargin.split(separators) if(!word.isEmpty))
words=words+(word.toLowerCase -> (words.getOrElse(word.toLowerCase,0)+1))
words.foreach(entry=>println("Word : "+entry._1+" count : "+entry._2))
私が理解している限り、Scalaでは、不変のデータ構造が可変のデータ構造よりも優先され、ジレンマに直面しているのでval
、結果がミュータブルに変換しながら不変に格納されると、ミュータブルを使用することを意味します。var
words
var
Map
words
val
Map
誰かがこの実存的な問題に対処する適切な方法について私に教えてもらえますか?