Created
September 3, 2015 09:56
-
-
Save sambaiz/e5325e12aaa4671dc9f9 to your computer and use it in GitHub Desktop.
Scala関数型デザイン&プログラミング10章
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// EXERCISE 10.1 | |
// 整数の加算と乗算、および論理演算子に対するMonoidインスタンスを考え出せ | |
trait Monoid[A] { | |
def op(a1: A, a2: A): A | |
def zero: A | |
} | |
val intAddition: Monoid[Int] = new Monoid[Int] { | |
def op(a1: Int, a2: Int) = a1 + a2 | |
val zero = 0 | |
} | |
val intMultiplication: Monoid[Int] = new Monoid[Int] { | |
def op(a1: Int, a2: Int) = a1 * a2 | |
def zero = 1 | |
} | |
val booleanOr: Monoid[Boolean] = new Monoid[Boolean] { | |
def op(a1: Boolean, a2: Boolean) = a1 || a2 | |
def zero = false | |
} | |
val booleanAnd: Monoid[Boolean] = new Monoid[Boolean] { | |
def op(a1: Boolean, a2: Boolean) = a1 && a2 | |
def zero = true | |
} | |
println(intMultiplication.op(10, 30)) | |
// EXERCISE 10.3 | |
// 引数および戻り値の型が同じである関数をendo関数と呼ぶことがある | |
// endo関数のモノイドを記述せよ | |
def endoMonoid[A]: Monoid[A => A] = new Monoid[A => A] { | |
def op(a1: A => A, a2: A => A) = (a) => a2(a1(a)) | |
def zero = (a) => a | |
} | |
println(endoMonoid.op((a: Int) => a * 2, (a: Int) => a + 2)(10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment