- Learning Functional Programming in Go
- Lex Sheehan
- 152字
- 2021-07-02 23:13:40
Use of expressions
Use of expressions (rather than statements) means that in FP, we pass a value to a function that typically transforms it in some way and then returns a new value. Since FP functions have no side effects, an FP function that does not return a value is useless and a sign of code smell.
In Chapter 1, Pure Functional Programming in Go, we saw that imperative programming focuses on the step-by-step mechanics of how a program operates, whereas in declarative programming, we declare what we want the results to be.
Here's an example of imperative programming:
var found bool
car_to_look_for := "Blazer"
cars := []string{"Accord", "IS250", "Blazer" }
for _, car := range cars {
if car == car_to_look_for {
found = true;
}
}
fmt.Printf("Found? %v", found)
Here's an example of declarative programming:
fmt.Printf("Found? %v", cars.contains("Blazer"))
We have less, declarative FP code that is easier to read.