开发者

to disassemble a data type ocaml

In case I have to disassemble a data type as its variable size, can I still use the "match and with, and if the answer is yes you could help me figure out how (I'm a beginner with this language), or do I or use other methods.

the type defined is this :

type 'state formula = 
  | And      of 'state formula list
  | Or       of 'state formula list
  | Literal  of 开发者_开发知识库bool
  | Variable of 'state  

from the examples I've seen the "match and with" is used when the structure of the static type was, in my case as I do?


So here's an example which uses match to work with your formula type:

type 'state formula = | And of 'state formula list | Or of 'state formula list | Literal of bool | Variable of 'state

let rec count_vars form = match form with
| And forms 
| Or forms -> List.fold_left (+) 0 (List.map count_vars forms)
| Literal _ -> 0
| Variable _ -> 1

let formula = And [ Variable "q0"; Or[ Variable "q1";Variable "q2"]; Variable "q3"]

let vars_in_formula = count_vars formula (* 4 *)


If you want to manipulate the type, you can use patter matching(among other things, but I find this the most elegant). It's essentially syntactical sugar for Match with.

For example:

let identify_formula=function
And(l) -> 0
|Or(l) -> 1
|Literal(b) -> 2
| Variable(v) -> 3;;

For a less trivial example of how to manipulate types:

type  l=Cons of int*l
    | Nil;;

let rec sum_l=function
Cons(hd,tl)->hd+ sum_l(tl)
| Nil-> 0;;

sum_l(Cons(1,Cons(2,Cons(3,Nil))));; (*r6*)


Maybe you would like a code example to adapt to your needs.

type 'state formula =
  | Literal of bool
  | And of 'state formula list
  | Or of 'state formula list
  | Variable of 'state

let rec eval variable_env formula =
  match formula with
    | Literal b -> b
    | Variable v -> variable_env v
    | And formulas -> List.for_all (eval variable_env) formulas
    | Or formulas -> List.exists (eval variable_env) formulas

(* same as eval, different code *)
let rec eval2 env = function
  | Literal b -> b
  | Variable v -> env v
  | And [] -> true
  | And (hd::tl) -> eval env hd && eval2 env (And tl)
  | Or [] -> false
  | Or (hd::tl) -> eval env hd || eval2 env (Or tl)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜