DAY 26
0
Software Development

1. 一等公民和高階函數
2. 純函數/類似數學函數
3. 宣告式編程

## 特性與語法

### 1. 第一公民特性

``````auto sum = [](auto x, auto y){
auto sum = x + y;
return sum;
};
int main(){
auto sums = sumOf(1,2);
}
``````

### 2. 高階函數特性

``````#include <unordered_map>
#include <functional>
using namespace std;

auto difference = [](auto x, auto y){ return x-y; };
auto product = [](auto x, auto y){ return x * y; };
auto quotient = [](auto x, auto y){ return x/y; };
auto sum = [](auto x, auto y){ return x + y; };

unordered_map<char, function<double(double,double)>>  calculate = {
{'+',sum},
{'-',difference},
{'*',product},
{'/',quotient}
};
``````

### 3. 宣告式編程

``````int main(){
calculate['*'](3.5,2);
calculate['/'](9.5,2);
}
``````

``````7
4.75
``````

### 4. 高階函數（二）

Lambda也擁有高階函數的第二個特性，就是能自己返回函數了

``````using namespace std;

auto chooseSign = [](char sign){ return calculate[sign]; };

auto equation = [](auto x, auto y,char sign, auto z){
auto evaluate = chooseSign(sign);

for(auto i = 0;i<2000;i++){
if(evaluate(x,y) == z) return x;
else if(evaluate(x,y) == z) return -x;
}
return -1;
};
``````

### 6. 返回多個變數

``````#include<tuple>
auto return3Ints = []（auto a, auto b, auto c） -> tuple <int, int, int> {
return make_tuple（a, b, c）;
};

int main(){
auto [a,c,d] = return3Ints(1,7,3);
}
``````

C++ 30天屠龍記30