给出一个完整的程序总是好的:
{-# LANGUAGE ScopedTypeVariables #-}
import Data.SBV
pairCube :: SInteger -> Symbolic SBool
pairCube limit = do
(m :: SInteger) <- exists "m"
(n :: SInteger) <- exists "n"
(a :: SInteger) <- exists "a"
constrain $ m^(3::Integer) .== n^(2::Integer)
constrain $ m .< limit
return $ m + n .== a^(2::Integer)
main :: IO ()
main = print =<< allSat (pairCube 1000)
当我运行它时,我得到:
Main> main
Solution #1:
m = 0 :: Integer
n = 0 :: Integer
a = 0 :: Integer
Solution #2:
m = 9 :: Integer
n = 27 :: Integer
a = -6 :: Integer
Solution #3:
m = 1 :: Integer
n = -1 :: Integer
a = 0 :: Integer
Solution #4:
m = 9 :: Integer
n = 27 :: Integer
a = 6 :: Integer
Solution #5:
m = 64 :: Integer
n = 512 :: Integer
a = -24 :: Integer
Solution #6:
m = 64 :: Integer
n = 512 :: Integer
a = 24 :: Integer
Unknown
注意最后Unknown.
本质上,SBV查询了Z3,得到了6个解;当SBV问7号时,Z3说“不知道有没有其他办法”。使用非线性算术,这种行为是预期的。
为了回答原始问题(即找到 max m
),我将约束更改为:
constrain $ m .== limit
并将其与以下“驱动程序”相结合:
main :: IO ()
main = loop 1000
where loop (-1) = putStrLn "Can't find the largest m!"
loop m = do putStrLn $ "Trying: " ++ show m
mbModel <- extractModel `fmap` sat (pairCube m)
case mbModel of
Nothing -> loop (m-1)
Just r -> print (r :: (Integer, Integer, Integer))
在我的机器上运行了大约 50 分钟后,Z3 产生了:
(576,13824,-120)
因此,显然allSat
基于方法的 Z3 放弃的方式比我们修复m
和迭代自己所能达到的要早。对于非线性问题,期望任何更快/更好的东西对于通用 SMT 求解器来说都太过分了。