我在试验Coq的提取机制。我在Coq中为素数编写了一个简单的谓词,如下所示:
(***********)
(* IMPORTS *)
(***********)
Require Import Coq.Arith.PeanoNat.
(************)
(* helper'' *)
(************)
Fixpoint helper' (p m n : nat) : bool :=
match m,n with
| 0,_ => false
| 1,_ => false
| _,0 => false
| _,1 => false
| S m',S n' => (orb ((mult m n) =? p) (helper' p m' n))
end.
(**********)
(* helper *)
(**********)
Fixpoint helper (p m : nat) : bool :=
match m with
| 0 => false
| S m' => (orb ((mult m m) =? p) (orb (helper' p m' m) (helper p m')))
end.
(***********)
(* isPrime *)
(***********)
Fixpoint isPrime (p : nat) : bool :=
match p with
| 0 => false
| 1 => false
| S p' => (negb (helper p p'))
end.
Compute (isPrime 220).
(*****************)
(* isPrimeHelper *)
(*****************)
Extraction Language Haskell.
(*****************)
(* isPrimeHelper *)
(*****************)
Extraction "/home/oren/GIT/CoqIt/Primes.hs" isPrime helper helper'.在提取Haskell代码之后,我编写了一个简单的驱动程序来测试它。我遇到了两个问题:
Bool,而不是使用内置于布尔类型的Haskell。nat,所以我不能问isPrime 6,我必须使用S (S (...))。module Main( main ) where
import Primes
main = do
if ((isPrime (
Primes.S (
Primes.S (
Primes.S (
Primes.S (
Primes.S (
Primes.S ( O ))))))))
==
Primes.True)
then
print "Prime"
else
print "Non Prime"发布于 2019-03-18 21:09:36
发布于 2019-03-19 08:31:27
我在这里发布了一个完整的解决方案,以使这篇文章自我包含。希望别人能利用它。
(***********)
(* IMPORTS *)
(***********)
Require Import Coq.Arith.PeanoNat.
(************)
(* helper'' *)
(************)
Fixpoint helper' (p m n : nat) : bool :=
match m,n with
| 0,_ => false
| 1,_ => false
| _,0 => false
| _,1 => false
| S m',S n' => (orb ((mult m n) =? p) (helper' p m' n))
end.
(**********)
(* helper *)
(**********)
Fixpoint helper (p m : nat) : bool :=
match m with
| 0 => false
| S m' => (orb ((mult m m) =? p) (orb (helper' p m' m) (helper p m')))
end.
(***********)
(* isPrime *)
(***********)
Fixpoint isPrime (p : nat) : bool :=
match p with
| 0 => false
| 1 => false
| S p' => (negb (helper p p'))
end.
Compute (isPrime 220).
(********************************)
(* Extraction Language: Haskell *)
(********************************)
Extraction Language Haskell.
(***************************)
(* Use Haskell basic types *)
(***************************)
Require Import ExtrHaskellBasic.
(****************************************)
(* Use Haskell support for Nat handling *)
(****************************************)
Require Import ExtrHaskellNatNum.
Extract Inductive Datatypes.nat => "Prelude.Integer" ["0" "succ"]
"(\fO fS n -> if n Prelude.== 0 then fO () else fS (n Prelude.- 1))".
(***************************)
(* Extract to Haskell file *)
(***************************)
Extraction "/home/oren/GIT/CoqIt/Primes.hs" isPrime helper helper'. 这是司机:
module Main( main ) where
import Primes
import Prelude
main = do
if ((isPrime 220) == True)
then
print "Prime"
else
print "Non Prime"有趣的是,Coq的慢速Compute (isPrime 220)和Haskell的编译(和优化!)之间存在着巨大的时间差。超快版本的(is Prime 220)。
https://stackoverflow.com/questions/55229385
复制相似问题