Skip to content

Instantly share code, notes, and snippets.

@1206yaya
Created January 20, 2015 07:38
Show Gist options
  • Save 1206yaya/430580f6a574f77a26c8 to your computer and use it in GitHub Desktop.
Save 1206yaya/430580f6a574f77a26c8 to your computer and use it in GitHub Desktop.
scala 基本
def max(x: Int, y: Int): Int = {
if (x > y) x
else y
}
def max2(x: Int, y: Int) = if (x > y) x else y
val list: List[String] = List[String]("A", "B", "C\n")
println(max(1, 2))
println(max2(3, 4))
list.foreach(item => print(item)) // ABC
list.foreach(print) // ABC
// <- は ∈ 集合の関係を表す。for item in list
for (item <- list) // ABC
print(item)
< 実行結果 >
2
4
ABC
ABC
ABC
println("------------------- 配列を型でパラメーター化する 配列は常にミュータブル-------------------")
val greetStrings = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"
for (i <- 0 to 2)
print(greetStrings(i))
greetStrings.update(0, "Well come")
greetStrings.update(1, ", ")
greetStrings.update(2, "world!\n")
for (i <- 0.to(2))
print(greetStrings.apply(i))
println("------------------- 配列の作成と初期化 -------------------")
val numNames = Array("zero", "one", "two")
// applyメソッドは、Arrayコンパニオンオブジェクトで定義されており、可変個の引数をとる
val numNames2 = Array.apply("zero", "one", "two")
println("------------------- リストを使う リストは常にイミュータブル-------------------")
val oneTwo = List(1, 2)
val threeFour = List(3, 4)
// ::: は、2つのリストを連結するメソッド
val oneTwoThreeFour = oneTwo ::: threeFour
println(oneTwo + " and " + threeFour + " were not mutated.")
println("Thus, " + oneTwoThreeFour + " is a new list.")
val twoThree = List(2, 3)
// :: (construct) は、既存のリストの先頭に新しい要素を追加して得られるリストを返す
val oneTwoThree = 1 :: twoThree
println(oneTwoThree)
val oneTwoThree2 = 1 :: 2 :: 3 :: Nil
println(oneTwoThree2)
println("------------------- タプルを使う リストとは異なり、異なる型の要素を持つことができる -------------------")
val pair = (99, "Luftballons")
println(pair._1) // _1フィールドの99にアクセスしている
println(pair._2)
println("------------------- 集合とマップを使う -------------------")
import scala.collection.immutable.HashSet
val hashSet = HashSet("Tomatoes", "Chilies")
println(hashSet + "Coriander")
// ミュータブルマツブの作成・初期化・操作
import scala.collection.mutable.Map
val treasureMap = Map[Int, String]()
treasureMap += (1 -> "Go to island.")
treasureMap += (2 -> "Find big X on ground.")
treasureMap += (3 -> "Dig.")
println(treasureMap(2))
// イミュータブルマップの作成・初期化・操作 デフォルトがイミュータブルなので、インポートは不要
val romanNumeral = Map(
1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V"
)
println(romanNumeral(4))
println("------------------- 関数型のスタイルを見分ける -------------------")
def formatArgs(args: Array[String]) = args.mkString("\n")
print(formatArgs(greetStrings))
val res = formatArgs(Array("zero", "one", "two"))
// assertメソッドは、引数のBooleanをチェックし、値がfalse ならばAssertionErrorを投げる。渡されたBooleanがtrueなら、そのまま何もせずに戻ってくる。
assert(res == "zero\none\ntwo")
println("------------------- ファイルから行を読み出す -------------------")
import scala.io.Source
// getLinesメソッドは、1度に1行ずつ提供するIterator[String]を返す。
for (line <- Source.fromFile("/tmp/scalaLesson.txt").getLines())
println(line.length +" "+ line)
val lines = Source.fromFile("/tmp/scalaLesson.txt").getLines().toList
// 引数の文字列の長さが何字で表示できるかを計算する
def widthOfLength(s: String) = s.length.toString.length // yamazaki ayaなら2 komatuなら1 quuなら1
// var maxWidth = 0
// for (line <- lines)
// maxWidth = maxWidth.max(widthOfLength(line))
// reduceLeftメソッドは、渡された関数をlinesの先頭2行に適用し、このときの結果値とlinesの次の要素とを対象として再び同じこの関数を適用する。
// リストの要素を全部処理するまでこれを繰り返す。最終的にlongestLineにはyamazaki ayaが入る
val longestLine = lines.reduceLeft(
(a, b) => if (a.length > b.length) a else b
)
val maxWidth = widthOfLength(longestLine) // 2
for (line <- lines) {
val numSpaces = maxWidth - widthOfLength(line)
val padding = " " * numSpaces
println(padding + line.length +" | "+ line)
}
yamazaki aya
komatu
quu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment