Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml syntax error in function

I have to create a function which will display each element from a set of strings. I did the following:

module S = Set.Make(String);;
module P = Pervasives;;
let write x = (
        P.print_string("{"); let first = true;
    S.iter (fun str -> (if first then () else P.print_string(","); P.print_string(str))) x;
    P.print_string("}");
    P.print_newline
  );;
  ^

At the end of the program (where I placed that sign) it appears I have an error: Syntax error: operator expected. Please help me solve this.

like image 946
Andrew Avatar asked Dec 20 '22 22:12

Andrew


2 Answers

I believe your syntactic problem is with let. Except in top-level code (outermost level of a module), let must be followed by in.

There are many other problems with this code, but maybe this will let you find the next problem :-)

A few notes:

Variables in OCaml are immutable. So your variable named first will always be true. You can't change it. This (seemingly minor) point is one of the keys to functional programming.

You don't need to reference the Pervasives module by name. That's why it's called "pervasive". You can just say print_string by itself.

Your last call to print_newline isn't a call. This expression just evaluates to the function itself. (You need to give it an argument if you want to call the function.)

like image 134
Jeffrey Scofield Avatar answered Dec 22 '22 12:12

Jeffrey Scofield


Try replacing the semicolon after the let first = true with the keyword in.

like image 25
Andreas Rossberg Avatar answered Dec 22 '22 10:12

Andreas Rossberg