功能证明(Haskell)

时间:2010-07-15 03:00:44

标签: haskell functional-programming proof

我读了RWH失败了;而不是一个退出,我命令 Haskell:功能编程工艺。现在我对第146页的这些功能证明感到好奇。特别是我试图证明8.5.1 sum (reverse xs) = sum xs。我可以做一些感应证明,但后来我卡住了..

HYP:

sum ( reverse xs ) = sum xs

BASE:

sum ( reverse [] ) = sum []

Left  = sum ( [] ) (reverse.1)
      = 0          (sum.1)

Right = 0          (sum.1)

INDUCTION:

sum ( reverse (x:xs) ) = sum (x:xs) 

Left = sum ( reverse xs ++ [x] )    (reverse.2)

Right = sum (x:xs)   
      = x + sum xs                  (sum.2)

所以现在我只是试图证明Left sum ( reverse xs ++ [x] )等于Right x + sum xs,但这离我开始的地方并不太远{ {1}}。

我不太确定为什么需要证明这一点,使用sum ( reverse (x:xs) ) = sum (x:xs)(通过defn)的符号证明似乎是完全合理的,因为+是可交换的(关节)然后是reverse x:y:z = z:y:x

4 个答案:

答案 0 :(得分:24)

sum (reverse [])     = sum []                     -- def reverse
sum (reverse (x:xs)) = sum (reverse xs ++ [x])    -- def reverse
                     = sum (reverse xs) + sum [x] -- sum lemma below
                     = sum (reverse xs) + x       -- def sum
                     = x + sum (reverse xs)       -- commutativity assumption!
                     = x + sum xs                 -- inductive hypothesis
                     = sum (x:xs)                 -- definition of sum

然而,关联性和可交换性的基本假设并非严格保证,对于许多数字类型(例如FloatDouble,这些假设都会被违反。< / p>

引理:sum (xs ++ ys) == sum xs + sum ys给出了(+)

的相关性

证明:

sum ([] ++ ys)     = sum ys           -- def (++)
                   = 0 + sum ys       -- identity of addition
                   = sum [] ++ sum ys -- def sum

sum ((x:xs) ++ ys) = sum (x : (xs ++ ys))  -- def (++)
                   = x + sum (xs ++ ys)    -- def sum 
                   = x + (sum xs + sum ys) -- inductive hypothesis
                   = (x + sum xs) + sum ys -- associativity assumption!
                   = sum (x:xs) + sum ys   -- def sum

答案 1 :(得分:6)

基本上你需要显示

sum (reverse xs ++ [x]) = sum (reverse xs) + sum [x]

然后很容易导致

                        = x + sum (reverse xs)
                        = x + sum xs  -- by inductive hyp.

问题是要显示sum分配在列表连接上。

答案 2 :(得分:4)

使用和的定义分解(求和xs ++ [x])和x + sum(反向(xs)),并使用归纳假设你知道sum(reverse(xs))= sum( XS)。但我同意,对于像这样的问题,归纳是过度的。

答案 3 :(得分:3)

这就是我认为你被困住的地方。你需要证明一个引理

的引理
sum (xs ++ ys) == sum xs + sum ys

为了证明这个定律你必须假设加法是关联的,这对整数和有理数都是正确的。

然后,你还需要假设加法是可交换的,对于整数和有理数,也适用于浮点数。


题外话:你的证明样式对我来说很奇怪。如果您使用Graham Hutton's book中的样式,我认为您可以更轻松地编写这些样张。