8 Ocak 2021 Cuma

Functional Programming Monad

Giriş
Açıklaması şöyle
Monads are heavily used in most functional programming languages. In Haskell, for example, they are essential and appear everywhere, in all kinds of applications and libraries.                            

On the other hand, monads are rarely used in popular, non-pure-functional programming languages like C#, Java, Python, etc.
Anladığım kadarıyla Monad kullanarak Function Composition yapabiliyoruz. Yani Java ile düşünürsek nested function call gibi düşünülebilir. Bu çağrı zincirinde önce string'in başında/sonunda bulunan boşluklar temizlenir, büyük harfe çevrilir ve başına ünlem işareti konulur.
return appendExclam ( toUpperCase ( trim ( sentence ) ) );
Ancak bu kullanımda bir eksiklik var. Eğer hata bulunursa bunu yukarıdaki metoda geçme yolu yok. Monad bunu da hallediyor.

Kotlin Either Monad
Açıklaması şöyle
- Either type represents values with two possibilities, either Left or Right
- Convention dictates that Left is used for Failure and Right is used for Success.
- Mnemonic: Right also means correct.
İskeleti şöyle
sealed class Either<out A, out B> {
    data class Left<A>(val value: A) : Either<A, Nothing>()
    data class Right<B>(val value: B) : Either<Nothing, B>()
}
Örnek
Şöyle yaparız
data class Account private constructor(val balance: BigDecimal) {

  companion object {
    fun create(initialBalance: BigDecimal): Either<NegativeAmount, Account> =
      if (initialBalance < 0) Either.Left(NegativeAmount)
      else Either.Right(Account(initialBalance))
  }
}




Hiç yorum yok:

Yorum Gönder