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

8.5.3. 건전성 증명🔗

LeanForProofs/Chapter08/Section05/Subsection03.lean을 연다.

건전성을 증명할 때는 탐색 결과가 true라는 가정에서 시작한다. 이 가정은 함수가 값을 돌려준 뒤에 사용할 수 있는 정보다. 임의의 target을 고정하고 리스트에 대해 구조적 귀납법을 적용한다. 빈 리스트에서는 linearSearch target []가 false로 계산되므로 성공했다는 가정에서 모순을 얻는다.

cons 분기에서 머리 x가 탐색 대상과 같으면 머리 자체가 대상의 포함을 보장한다. 두 값이 다르면 전체 리스트의 탐색 결과는 꼬리의 탐색 결과다. 따라서 꼬리의 결과도 true이다. 귀납 가정으로 대상이 꼬리에 포함됨을 얻고, 이를 전체 리스트의 포함으로 옮긴다. 그림 8.20에서 두 분기의 증명이 어떤 근거로 같은 결론에 닿는지 비교한다.

성공을 가정한 cons 분기에서 머리가 대상과 같으면 머리에서 포함을 얻는다. 머리가 다르면 꼬리의 성공과 귀납 가정으로 꼬리에 포함됨을 얻는다. 두 경우 모두 전체 리스트에서 포함을 증명한다.
그림 8.20 탐색의 성공으로부터 원소의 포함 관계를 얻는 두 경우

by_cases로 x = target과 그 부정을 나눈다. 첫 분기에서는 heq.symm으로 얻은 target = x를 Or.inl에 넣고, List.mem_cons.mpr로 포함 관계를 만든다. 둘째 분기에서는 simpa [linearSearch, heq] using h가 성공했다는 가정에서 현재 원소의 비교를 정리해 꼬리의 성공 ht를 얻는다. List.mem_cons_of_mem은 ih ht가 주는 꼬리의 포함 관계를 전체 리스트로 확장한다.

theorem linearSearch_sound (target : Nat) (xs : List Nat) : linearSearch target xs = true → target ∈ xs := target:Natxs:List Nat⊢ linearSearch target xs = true → target ∈ xs induction xs with target:Nat⊢ linearSearch target [] = true → target ∈ [] All goals completed! 🐙 target:Natx:Natxs:List Natih:linearSearch target xs = true → target ∈ xs⊢ linearSearch target (x :: xs) = true → target ∈ x :: xs target:Natx:Natxs:List Natih:linearSearch target xs = true → target ∈ xsh:linearSearch target (x :: xs) = true⊢ target ∈ x :: xs target:Natx:Natxs:List Natih:linearSearch target xs = true → target ∈ xsh:linearSearch target (x :: xs) = trueheq:x = target⊢ target ∈ x :: xstarget:Natx:Natxs:List Natih:linearSearch target xs = true → target ∈ xsh:linearSearch target (x :: xs) = trueheq:¬x = target⊢ target ∈ x :: xs target:Natx:Natxs:List Natih:linearSearch target xs = true → target ∈ xsh:linearSearch target (x :: xs) = trueheq:x = target⊢ target ∈ x :: xs All goals completed! 🐙 target:Natx:Natxs:List Natih:linearSearch target xs = true → target ∈ xsh:linearSearch target (x :: xs) = trueheq:¬x = target⊢ target ∈ x :: xs target:Natx:Natxs:List Natih:linearSearch target xs = true → target ∈ xsh:linearSearch target (x :: xs) = trueheq:¬x = targetht:linearSearch target xs = true⊢ target ∈ x :: xs All goals completed! 🐙

ih ht에 커서를 놓고 Lean InfoView에서 그 타입이 target ∈ xs인지 확인한다. 다음 소절에서는 대상이 들어 있다는 증명을 가정으로 받아, 거꾸로 탐색의 성공을 얻는다.