9.6.2. 삽입 연산의 비용
[2, 4, 6, 8]에 5를 넣으려면 2, 4, 6과 비교한다. 6에서 조건이 처음 참이 되어 그 앞에 5를 놓는다. 9를 넣을 때는 네 원소를 모두 지나 맨 끝에 넣는다. 그림 9.18에서 삽입할 수를 바꾸고, 같은 값 앞에도 삽입할 수 있음을 확인한다.
insertCost는 insertNat과 같은 비교 조건에서, 반환할 리스트 대신 비교 횟수를 계산한다. 빈 리스트에서는 0이다. 머리에서 끝나면 1이고, 꼬리까지 진행하면 꼬리의 비용에 지금 비교한 1을 더한다.
def insertCost (x : Nat) : List Nat → Nat
| [] => 0
| y :: ys =>
if x ≤ y then 1
else insertCost x ys + 1
#eval insertCost 1 [2, 4, 6, 8]
#eval insertCost 5 [2, 4, 6, 8]
#eval insertCost 9 [2, 4, 6, 8]
세 비용은 차례로 1, 3, 4다. 어느 경우에도 같은 위치를 두 번 비교하지 않으므로 비용은 삽입을 받는 리스트의 길이 이하다. 9.3.3절의 선형 탐색에서처럼 꼬리의 비용 상한을 귀납 가정으로 받아, 재귀 호출이 있는 경우 양쪽에 1을 더한다.
theorem insertCost_le_length (x : Nat) (xs : List Nat) :
insertCost x xs ≤ xs.length := x:Natxs:List Nat⊢ insertCost x xs ≤ xs.length
induction xs with
x:Nat⊢ insertCost x [] ≤ [].length All goals completed! 🐙
x:Naty:Natys:List Natih:insertCost x ys ≤ ys.length⊢ insertCost x (y :: ys) ≤ (y :: ys).length
x:Naty:Natys:List Natih:insertCost x ys ≤ ys.lengthh:x ≤ y⊢ insertCost x (y :: ys) ≤ (y :: ys).lengthx:Naty:Natys:List Natih:insertCost x ys ≤ ys.lengthh:¬x ≤ y⊢ insertCost x (y :: ys) ≤ (y :: ys).length
x:Naty:Natys:List Natih:insertCost x ys ≤ ys.lengthh:x ≤ y⊢ insertCost x (y :: ys) ≤ (y :: ys).length All goals completed! 🐙
x:Naty:Natys:List Natih:insertCost x ys ≤ ys.lengthh:¬x ≤ y⊢ insertCost x (y :: ys) ≤ (y :: ys).length All goals completed! 🐙
- 연습문제 9.6.1 삽입 연산의 최소 비용
x ≤ y를 가정하고insertCost x (y :: ys) = 1을insertCost_first로 증명한다. 이어 모든x,y,ys에 대해1 ≤ insertCost x (y :: ys)를insertCost_ge_one으로 증명한다.LeanForProofs/Chapter09/Section06/Subsection02.lean의end AlgorithmCost바로 위에 두 정리를 추가한다. 저장한 뒤 실습 저장소 루트에서lake build LeanForProofs.Chapter09.Section06.Subsection02를 실행한다.