Functional programming 在OCaml中操作循环内部的不可变变量
我在OCaml中有以下代码。我已经定义了所有必需的ESAR函数,并对它们进行了逐步测试。评估应该可以很好地工作,但我没有成功地在while中操纵变量。如何使x、vn、v改变它们的值?我想我应该像rec循环一样重写while,但无法准确地计算: 以下是代码的其余部分:Functional programming 在OCaml中操作循环内部的不可变变量,functional-programming,ocaml,Functional Programming,Ocaml,我在OCaml中有以下代码。我已经定义了所有必需的ESAR函数,并对它们进行了逐步测试。评估应该可以很好地工作,但我没有成功地在while中操纵变量。如何使x、vn、v改变它们的值?我想我应该像rec循环一样重写while,但无法准确地计算: 以下是代码的其余部分: 而循环属于OCaml中的命令式编程部分 基本上,您不能在中修改不可变变量,而或用于循环或任何地方 要使变量可变,您需要像let var=ref…那样定义它ref是可变项的关键字 阅读以下两章: 你可以将x,vn,v定义为ref
而
循环属于OCaml中的命令式编程部分
基本上,您不能在中修改不可变变量,而或用于循环或任何地方
要使变量可变,您需要像let var=ref…
那样定义它ref
是可变项的关键字
阅读以下两章:
你可以将x,vn,v
定义为ref
s,但我想这会很难看
我建议您以功能性的方式思考代码
由于您没有在此处放置函数ens
等,因此我无法为u生成一个优化示例。我可以在此处添加它们,我将编辑我的帖子。感谢您的回复。我有伪代码中的算法,我已经单独实现了所需的函数,并且在我尝试在OCaml中进行翻译之后。使用ref bea不起作用,因为我需要对它们使用预定义的集合函数(移除、选择等)@Kate07什么是=>和?你能用英语简要介绍一下你代码的目标吗?我想我已经找到了解决方案。算法的目标是测试公式是否是重言式,但比构建真值表更有效。
Pseudocode:
input : f formula
output: yes if f valid
else not
begin:
V =set of prop variables
eliminate from f => and <=>
while (V is not empty)
choose x from V
V =V -{x}
replace f with f[x->true]&&f[x->false]
simplify as much as possible f
if f is evaluated with true then return true
else if (not f) is evaluated true then return false
end if
end while
return false
end
type bexp = V of
| string
| B of bool
| Neg of bexp
| And of bexp * bexp
| Or of bexp * bexp
| Impl of bexp * bexp
| Eqv of bexp * bexp
module StringSet=Set.make(String)
let is_valide f=
let v= stringset_of_list (ens f []) in (*set of all variables of f *)
let g= elim f in (*eliminate => and <=> *)
let quit_loop=ref false in
while not !quit_loop
do
let x=StringSet.choose v in
let vn=StringSet.remove x v in
if StringSet.is_empty vn=true then quit_loop:=true;
let h= And( replace x (B true) g ,replace x (B false) g)in
let j=simplify h in
if (only_bools j) then
if (eval j) then print_string "yes"
else print_string "not"
done
let tautology f =
let rec tautology1 x v g =
let h= And( remplace x (B true) g ,remplace x (B false) g)in
let j= simplify h in
if not (only_bools j) then tautology (StringSet.choose (StringSet.remove x v) (StringSet.remove x v) j
else
if (eval1 j) then print_string "yes \n " else
if (eval1 (Neg (j))) then print_string "not \n";
in tautology1 (StringSet.choose (stringset_of_list (ens f [])) (stringset_of_list (ens f [])) (elim f);;