문제

I have the following code statement:

let execute command = 
match command with
|Skip -> ()
|Changestate (l,r) -> (let l = ref r)
|_ -> failwith "Not a command"

when I run this in the toplevel, I get the following error:

1 let execute command = 
2 match command with
3 |Skip -> ()
4 |Changestate (l,r) -> (let l = ref r)
5 |_ -> failwith "Not a command";;
6 Error: Syntax error

The syntax error appears to occur at the parenthesis at the end of line 4. What I would like this line to do is to change the value at l to a reference variable to r, but return no actual value.

도움이 되었습니까?

해결책

Well, camlspotter already gave a great answer, but here's what I was going to say.

First, there's no OCaml expression let var = expr, except at the top level of a module where it defines the exported names of the module.

In all other places, the expression looks like let var = expr1 in expr2. So your code is wrong syntactically, as the compiler is telling you.

Second, even if your code was syntactically correct, the expression let l ... defines a new variable l with no relation to the one in the pattern just before it.

Third, you don't give the types of anything so it's hard to help you (exactly as camlspotter says). But generally speaking, you can't change the value of l. An identifier in OCaml is bound immutably to its value.

If l is bound (immutably!) to a reference of the correct type, you can set the value in the reference with the expression l := r.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top