I ha开发者_运维百科ve defined this type :
type state= L of state_simple * int | N of state * int | State of int
if I only need the integer of "State" What should I do?
here is the code:
let prove state ch a =
(*"state" is of type State st, i need the integer st*)
let (_,p,suc,_) =game.(i) in
let x = ref[] in
let y = ref(Variable a.(suc.(0)) )in
let l = Array.length suc in
x :=a.(suc.(0)) :: !x;
if (p=0) then
(if (l <> 1) then
(for i=1 to l-1 do
x := ((a.(suc.(i))) :: !x)
done;
!x;;
I would first recommend trying to better understand immutability and functional techniques as you don't need references for a lot of what you are doing. Here is how I would get the integer:
let prove st ch a =
let i = match st with
| State x -> x
| L _ | N _ -> assert false (* or raise an exception *)
in
let (_,p,suc,_) =game.(i) in
let x = ref[] in
let y = ref(Variable a.(suc.(0)) )in (* are you using y anywhere? *)
let l = Array.length suc in
x :=a.(suc.(0)) :: !x;
if (p=0) then
(if (l <> 1) then
(for i=1 to l-1 do
x := ((a.(suc.(i))) :: !x)
done;
!x;;
You don't seem to be using y, I'm not sure if that's due to a typo or something else. Also you can construct your list x
functionally using recursion:
let prove st ch a =
let i = match st with
| State x -> x
| L _ -> assert false (* or raise an exception *)
| N _ -> assert false
in
let (_,p,suc,_) =game.(i) in
let l = Array.length suc in
let rec loop x lst =
if x >= l then
lst
else
loop (x+1) (a.(suc.(i)) :: lst)
in
if (p=0) && (l <> 1) then
loop 1 [a.(suc.(0))]
else
[]
EDIT: After reading through some comments, it sounds like you are confused about what constitutes a type in OCaml.
type state= L of state_simple * int | N of state * int | State of int
creates a new type called state
. State(2)
and N(State(3), 2)
have the same type, but different values. If I write a function with the signature val f : state -> int
(that is, a function named f
that takes a state
and returns an int
), I can pass that function State(2)
or N(N(State(3), 4), 2)
or anything else.
Since you want the function prove
to only accept a state
whose value is State(x)
, you might want to rethink the way you are calling prove
. Maybe prove
should just take an int
instead of a state
, and the caller of prove
can do the pattern matching.
If this is too cumbersome (prove
is called in multiple places) then having the match statement in the function makes sense, as long as bad matches (L_
and 'N_') are handled properly.
If I've understood You correctly, something like:
match foo with
| State i -> do_something_with_integer i
| _ -> ()
精彩评论