高階関数は他の関数をパラメーターとして受け取る、もしくは結果として関数を返します。 このようなことができるのは、Scalaでは関数が第一級値 (first-class value) だからです。 用語が少し紛らわしいかもしれませんが、 ここでは”高階関数”というフレーズを関数をパラメーターとして受け取る、または関数を返すメソッドと関数の両方に対して使います。 もっとも一般的な例の1つは、Scalaのコレクションで利用可能な高階関数mapです。 val salaries = Seq(20000, 70000, 40000) val doubleSalary = (x: Int) => x * 2 val newSalaries = salaries.map(doubleSalary) // List(40000, 140000, 80000) doubleSalaryはIntxを1つだけ受け
I think the accepted answer is great, but it seems many people have failed to grasp some fundamental points. First, Scala's for comprehensions are equivalent to Haskell's do notation, and it is nothing more than a syntactic sugar for composition of multiple monadic operations. As this statement will most likely not help anyone who needs help, let's try again… :-) Scala's for comprehensions is synt
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 5.2, “How to call a method on a superclass in Scala.” Problem To keep your Scala code DRY (“Don’t Repeat Yourself ”), you want to invoke a method that’s already defined in a parent class or trait. Solution In the basic use case, the syntax to invoke a method in an immediate parent class is the same as
こういうことができます scala> def kakezan(x: Int, y: Int) = x * y kakezan: (x: Int, y: Int)Int scala> kakezan(3, 7) res1: Int = 21 scala> def curried_kakezan(x: Int)(y: Int) = x * y curried_kakezan: (x: Int)(y: Int)Int 使い方は、というとcurryingを作った後で使い方はまず最初の第1パラメーターを代入して関数を呼び出しますと 以下のようなエラーが出てしまいます どうやらそのカラーリングの関数の後あとと言うか関数はどれぐらいの引数を受け取るのかというような情報を与えてやらないとうまく動作しない これは個人的には分かりづらくて面白くありませんがそういう仕様です このアンダースコアの書き方は例えば二
list match { case List(1, 2, xs: _*) => ??? // xsはリストで取得できる case List(1, 2, _: _*) => ??? // 束縛しない場合 case _ => ??? } この例では、リストが1と2から始まる場合に、これに続く要素をリストとして取得しています。 この記述方法が関数リテラル等における可変長引数の記法と同じなので「可変長引数パターン」と呼ばれます。 変数に束縛する必要がない場合にはアンダースコア(_)で代替します。 使い方を具体的に見てみましょう。 def go(list: Seq[Int]): Unit = { list match { case List(1, 2, xs: _*) => println(s"3番目以降: $xs") // A case List(1, _ : _*) => println(s"1
Scalaでデータなどを扱うときにはcase classを使うのが一般的である。 このcase classはコンパニオンオブジェクトに書くのが当たり前のようになっているがそれはなぜか。 ScalaでもJavaと同様、インナークラスを定義できる。 しかし、その違いとして「パス依存性」という特徴がある。 インナークラスの型はどのアウタークラスから生成されたかで決まる。 REPLでアウタークラスとインナークラスを定義し、インスタンスを2つ作る。 var変数にインスタンスを再代入しようとすると、type mismatchエラーとなることがわかる。 scala> class Outer { | class Inner { | private val hoge = "hoge" | } | } defined class Outer scala> val o1 = new Outer o1: Oute
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く