Imperative programming V.S. declarative programming
Programming: Imperative & Declarative
- Imperative Programming: “How to” – a language written for computers
- Operation statements
- Conditional statements
- Looping statements
- Declarative programming: “What to do” — a language written for people
- Functional programming
- DSL: Domain specific language
Consider the following questions:
Check the average score of the students in students and output the first place in the average score.
Given some definition code:
struct Student {
let name: String
let scores: [Subject: Int]}enum Subject: String.CaseIterable {
case Chinese.Math.English
}
let s1 = Student(
name: "Foo",
scores: [.Chinese: 86, .Math: 92, .English: 73])let s2 = Student(
name: "Bar",
scores: [.Chinese: 99, .Math: 52, .English: 97])let s3 = Student(
name: "Joe",
scores: [.Chinese: 91, .Math: 92, .English: 100])let students = [s1, s2, s3]
Copy the code
Here’s an attempt to solve this problem using imperative and functional programming, respectively:
Imperative programming
Tell the computer what to do step by step.
// Command.swift
var best: (Student.Double)?
for s in students {
var totalScore = 0
for key in Subject.allCases {
totalScore + = s.scores[key] ?? 0
}
let averageScore = Double(totalScore) /
Double(Subject.allCases.count)
if let temp = best {
if averageScore > temp.1 {
best = (s, averageScore)
}
} else {
best = (s, averageScore)
}
}
print(best?.0.name ?? "no students")
Copy the code
This is probably the way most of you are familiar with programming.
Declarative programming
Tell the computer what to do, and the computer decides what to do.
functional
// The function.swift
func average(_ scores: [Subject: Int]) -> Double {
return Double(scores.values.reduce(0.+)) / Double(Subject.allCases.count)
}
let bestStudent = students
.map { ($0, average($0.scores)) }
.sorted { $0.1 > The $1.1 }
.first
Copy the code
(Written in January 2021: I kind of like functions, but SICP hasn’t finished yet.) Update(2021.07.18): Now we’re done!!
I always like function, recommend everyone to see SICP (must put the inside of the code to write it again, or to the basic behind do not understand) 👀.
DSL
Such as SQL:
select name, avg(score) as avs_score
from scores group by name order by avg_score;
Copy the code
(I don’t like SQL. I hate group by keywords that are more than one word, so I use ORM every day for my projects.)
reference
Wang Wei (@onevcat) SwiftUI and Combine Programming Chapter 1