Reputation: 1210
I am new to OCaml and am trying to learn how to update dictionary and deal with if/else conditionals.
I wrote the following code to check whether the dictionary has some key. If not, add a default value for that key. Finally print it out.
module MyUsers = Map.Make(String)
let myGraph = MyUsers.empty;;
let myGraph = MyUsers.add "test" "preset" myGraph in
try
let mapped = MyUsers.find "test" myGraph
with
Not_found -> let myGraph = MyUsers.add "test" "default" myGraph in
Printf.printf "value for the key is now %s\n" (MyUsers.find "test" myGraph)
The error message I have now is syntax error for line 6: with
What is wrong here? Also, when to use in
;
or;;
?
I have done some google searches and understand that in
seems to define some scope before the next ;;
. But it is still very vague to me. Could you please explain it more clearly?
Upvotes: 1
Views: 665
Reputation: 66813
Your immediate problem is that, except at the top level, let
must be followed by in
. The expression looks like let
variable =
expression1 in
expression2. The idea is that the given variable is bound to the value of expression1 in the body of expression2. You have a let
with no in
.
It's hard to answer your more general question. It's easier to work with some specific code and a specific question.
However, a semicolon ;
is used to separate two values that you want to be evaluated in sequence. The first should have type unit
(meaning that it doesn't have a useful value).
In my opinion, the double semicolon ;;
is used only in the top-level to tell the interpreter that you're done typing and that it should evaluate what you've given it so far. Some people use ;;
in actual OCaml code, but I do not.
Your code indicates strongly that you're thinking imperatively about OCaml maps. OCaml maps are immutable; that is, you can't change the value of a map. You can only produce a new map with different contents than the old one.
Upvotes: 2