Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created June 2, 2016 02:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/81d966bdff21a94a725794f1bf3e2041 to your computer and use it in GitHub Desktop.
Save xuwei-k/81d966bdff21a94a725794f1bf3e2041 to your computer and use it in GitHub Desktop.
Foldable の foldLeft が型推論のためにああいうシグネチャになってる理由(引数の順番とシグネチャ)
scala> trait Foldable1[F[_]] { def foldLeft[A, B](fa: F[A], z: B)(f: (B, A) => B): B }
warning: there was one feature warning; re-run with -feature for details
defined trait Foldable1
scala> val list = new Foldable1[List] { def foldLeft[A, B](fa: List[A], z: B)(f: (B, A) => B) = fa.foldLeft(z)(f) }
list: Foldable1[List] = $anon$1@5884a914
scala> list.foldLeft(List(1,2,3), "")((x, y) => x + y.toString)
res0: String = 123
scala> trait Foldable2[F[_]] { def foldLeft[A, B](fa: F[A], z: B, f: (B, A) => B): B }
warning: there was one feature warning; re-run with -feature for details
defined trait Foldable2
scala> val list = new Foldable2[List] { def foldLeft[A, B](fa: List[A], z: B, f: (B, A) => B) = fa.foldLeft(z)(f) }
list: Foldable2[List] = $anon$1@393881f0
scala> list.foldLeft(List(1,2,3), "", (x, y) => x + y.toString)
<console>:14: error: missing parameter type
list.foldLeft(List(1,2,3), "", (x, y) => x + y.toString)
^
<console>:14: error: missing parameter type
list.foldLeft(List(1,2,3), "", (x, y) => x + y.toString)
^
scala> list.foldLeft(List(1,2,3), "", (x, y: Int) => x + y.toString)
<console>:14: error: missing parameter type
list.foldLeft(List(1,2,3), "", (x, y: Int) => x + y.toString)
^
scala> list.foldLeft(List(1,2,3), "", (x: String, y: Int) => x + y.toString) // 型書かないといけなくなる
res4: String = 123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment