Senior
Name and explain two key programming paradigms
sobes.tech AI
Answer from AI
Two key programming paradigms:
-
Imperative programming — describes an algorithm as a sequence of commands that change the program's state. Example: loops, assignments, conditional statements. In Go, this is the primary style, where we explicitly control the flow of execution.
-
Functional programming — based on using functions as first-class objects, avoiding mutable state and side effects. In Go, there are elements of functional style, such as higher-order functions, closures.
Example in Go demonstrating both paradigms:
// Imperative style
sum := 0
for _, v := range []int{1, 2, 3} {
sum += v
}
// Functional style using a higher-order function
func mapInts(slice []int, fn func(int) int) []int {
result := make([]int, len(slice))
for i, v := range slice {
result[i] = fn(v)
}
return result
}
squared := mapInts([]int{1, 2, 3}, func(x int) int { return x * x })