Giriş
Açıklaması şöyle. Yani yan Etkisi Yoktur ve Aynı Girdi İçin Aynı Sonucu Verir
Most sources define a pure function as having the following two properties:
- Its return value is the same for the same arguments.
- Its evaluation has no side effects.
Önemli Not
Object Oriented programlamaya alışkın olanların itirazı şöyle
  “This is puristic nonsense!” you say. “Intellectual masturbation! Software should be modeled after real-world, mutable objects!”
Functional programlamaya alışkın olanların itirazı da şöyle. Çünkü OO şeklinde yazılan bazı kodlar gerçekten çok büyük ve anlaması zor olabiliyor.
  You shouldn't need several hours to understand what a method, class, or package does. If you need a lot of mental effort to even start programming, you will run out of energy before you can produce quality. Reduce the cognitive load of your code and you will reduce its amount of bugs.
Aslında Functional veya Object Oriented programlamadan sadece birisini tercih etmek zorunda değiliz. Bu ikisi kolayca bir arada kullanılabiliyor.
Functinal Programming bize öncelikle kodu işlevsel daha küçük parçalara bölme imkanı veriyor. Buna "Partitioning by Functionality" veya "Breaking It Up Into Composable Units" diyebiliriz. Bu bölümleme esnasında yukarıdaki 2 kurala da uyunca anlaması, okuması ve test etmesi daha kolay kodlar ortaya çıkıyor
Pure Function Örnekleri
Örnek
Şöyle yaparız.
const add = (x, y) => x + y;
add(2, 4); // 6Impure Function Örnekleri
Örnek
Şu kod impure çünkü harici state'ı değiştiriyor.
Şu kod impure çünkü harici state'i okuyor veya tutuyor.
Functional dillerderde aşağıdaki gibi döngüler impure olarak kabul edilirler.
Örnek
Şu kod impure çünkü harici state'ı değiştiriyor.
let x = 2;
const add = (y) => {
  return x += y;
};
add(4); // x === 6 (the first time)
add(4); // x === 10 (the second time)Şu kod impure çünkü harici state'i okuyor veya tutuyor.
const exchangeRate =  fetchFromDatabase(); // evaluates to say 0.9 for today;
const dollarToEuro = (x) => {
  return x * exchangeRate;
};
dollarToEuro(100) //90 today
dollarToEuro(100) //something else tomorrowconst exchangeRate =  fetchFromDatabase(); // evaluates to say 0.9 for today;
const dollarToEuro = (x, exchangeRate) => {
  return x * exchangeRate;
};Functional dillerderde aşağıdaki gibi döngüler impure olarak kabul edilirler.
Döngüler diğer metodlar kullanılarak yapılır.intas_int(char*str) {intacc; /* accumulate the partial result */for(acc = 0; isdigit(*str); str++) { acc = acc * 10 + (*str - '0'); }returnacc; }
intas_int(char*str) {returnfold(takeWhile(isdigit, str), 0,intfunction(char*chr,intacc) {returnacc * 10 + (chr - '0'); }); }
 
 
Hiç yorum yok:
Yorum Gönder