DAY 14
1
Software Development

## Introduce Monoid

### 上一篇的解答：

``````sealed class Either<A, B>() {

class Left<A, B>(val value: A): Either<A, B>()
class Right<A, B>(val value: B): Either<A, B>()

fun <C> mapLeft(transform: (A) -> C): Either<C, B> {
return when(this) {
is Left -> Left(transform(value))
is Right -> Right(value)
}
}

fun <C> mapRight(transform: (B) -> C): Either<A, C> {
return when(this) {
is Left -> Left(value)
is Right -> Right(transform(value))
}
}

fun <R> fold(left: (A) -> R, right: (B) -> R): R {
return when(this) {
is Left -> left(value)
is Right -> right(value)
}
}
}
``````

# Definition

Monoid 就是一個集合，而且我們幾乎每天都用到他，只是我們使用的不是這個抽象，而是其他衍伸的實作，例如 String 及 List。那怎樣的集合能夠說是一個 Monoid 呢？首先，這集合裡面有一個二元運算子，這個二元運算子是保持其型別的。例如這個集合是一個整數集合，其運算子為加法，經過了這個二元運算子後，輸出也必須還是整數，如下：

``````val a: Int = 1
val b: Int = 2
val op: (Int, Int) -> Int = { first, second -> first + second }
val c: Int = op(a, b)
``````

``````ID       => Identity in this Monoid
a, b, c  => elements in the Monoid
op       => binary operation for this Monoid

a op ID = a                                   // 1  右單位元
ID op a = a                                   // 2  左單位元
(a op b) op c = a op (b op c) = a op b op c   // 3  結合律
``````

``````""             => Identity in this Monoid
"a", "b", "c"  => elements in the Monoid
+              => binary operation for this Monoid

"a" + "" = "a"                                            // 1  右單位元
"" + "a" = "a"                                            // 2  左單位元
("a" + "b") + "c" = "a" + ("b" + "c") = "a" + "b" + "c"   // 3  結合律
``````

``````1              => Identity in this Monoid
2, 3, 4        => elements in the Monoid
*              => binary operation for this Monoid

2 * 1 = 2                                      // 1  右單位元
1 * 2 = 2                                      // 2  左單位元
(2 * 3) * 4 = 2 * (3 * 4) = 2 * 3 * 4          // 3  結合律
``````

# Monoid in Programming

``````sealed class Maybe<T>{
class Some<T>(val value: T): Maybe<T>()
class None<T> : Maybe<T>()

fun <R> map(transform: (T) -> R): Maybe<R> {
return when(this) {
is Some -> Some(transform(value))
is None -> None()
}
}

// 這邊的實作會是什麼？
fun op(another: Maybe<T>): Maybe<T> = ?
}
``````

### Maybe 的 Associativity

``````Some(A) op Some(B) => Some(A)
(Some(A) op Some(B)) op Some(C) => Some(A) op Some(C) => Some(A)
Some(A) op (Some(B) op Some(C)) => Some(A) op Some(B) => Some(A)
``````

``````Some(A) op Some(B) => Some(B)
(Some(A) op Some(B)) op Some(C) => Some(B) op Some(C) => Some(C)
Some(A) op (Some(B) op Some(C)) => Some(A) op Some(C) => Some(C)
``````

``````fun first(other: Maybe<T>): Maybe<T> {
return when(this) {
is Some -> this
is None -> other
}
}

fun last(other: Maybe<T>): Maybe<T> {
return when(other) {
is Some -> other
is None -> this
}
}
``````

# 小結

### 1 則留言

0
hannahpun
iT邦新手 4 級 ‧ 2020-09-27 00:21:32

hannahpun iT邦新手 4 級 ‧ 2020-09-27 01:10:19 檢舉