Lean으로 배우는 증명가능한 프로그래밍

9.6.3. 삽입 정렬의 비용 함수🔗

x :: xs의 정렬 비용은 두 항의 합이다. 첫 항은 꼬리를 정렬할 때 이미 수행한 비교 횟수다. 둘째 항은 정렬된 꼬리 insertionSort xs에 x를 넣을 때의 비교 횟수다. 어느 위치에 삽입하는지를 알아야 둘째 항의 정확한 값을 구할 수 있다.

def insertionSortCost : List Nat → Nat | [] => 0 | x :: xs => insertionSortCost xs + insertCost x (insertionSort xs) 4#eval insertionSortCost [1, 2, 3, 4, 5] 10#eval insertionSortCost [5, 4, 3, 2, 1]

두 결과는 4와 10이다. 9.2.3절처럼 반환값에 비용을 함께 담을 수도 있다. insertWithCost는 삽입 결과와 비교 횟수를 돌려준다. 전체 정렬에서는 꼬리 정렬의 결과 ys를 삽입에 그대로 넘긴다. 두 단계의 비용 c₁과 c₂를 더해 최종 비용을 구한다.

def insertWithCost (x : Nat) : List Nat → List Nat × Nat | [] => ([x], 0) | y :: ys => if x ≤ y then (x :: y :: ys, 1) else let (zs, c) := insertWithCost x ys (y :: zs, c + 1) def insertionSortWithCost : List Nat → List Nat × Nat | [] => ([], 0) | x :: xs => let (ys, c₁) := insertionSortWithCost xs let (zs, c₂) := insertWithCost x ys (zs, c₁ + c₂) ([1, 2, 3, 4, 5], 4)#eval insertionSortWithCost [1, 2, 3, 4, 5] ([1, 2, 3, 4, 5], 10)#eval insertionSortWithCost [5, 4, 3, 2, 1]

Lean InfoView에서 두 쌍의 첫째 성분이 [1, 2, 3, 4, 5]임을 확인한다. 둘째 성분은 각각 비용 함수가 내놓은 4와 10이다. 모든 입력에서 이 관계를 증명하려면, 먼저 삽입을 수행하는 함수에서 반환한 두 성분을 각각 기존 정의와 연결한다.

연습문제 9.6.2 계산 결과와 계산 비용의 일치

(insertWithCost x xs).1 = insertNat x xs와 (insertWithCost x xs).2 = insertCost x xs를 증명한다. 두 성분을 한 번에 묶은 순서쌍의 등식부터 증명해도 된다. 이어 그 결과를 이용해 전체 정렬의 두 명제를 증명한다.

∀ (xs : List Nat), (insertionSortWithCost xs).fst = insertionSort xs : Prop#check ∀ xs : List Nat, (insertionSortWithCost xs).1 = insertionSort xs ∀ (xs : List Nat), (insertionSortWithCost xs).snd = insertionSortCost xs : Prop#check ∀ xs : List Nat, (insertionSortWithCost xs).2 = insertionSortCost xs