andrewhunter
andrewhunter

Reputation: 183

Ocaml if-then-else Syntax Error

Why is this Ocaml statement giving me a syntax error?

let a = 0;; if a = 0 then let b = 0;;

Do if then else statements always have to return a value?

EDIT: Here is the code I am struggling with. I want to apply this function over a list with the map function. The function is supposed to look at each word in the list wordlist and add to the stringmap. If it has already been added to the string map then add 1 to its password.

module StringMap = Map.Make(String)
let wordcount = StringMap.empty
let findword testword =
    let wordcount = (if (StringMap.mem testword wordcount) 
    then (StringMap.add testword ((StringMap.find testword wordcount)+1) wordcount)
    else (StringMap.add testword 1 wordcount))
List.map findword wordlist

Upvotes: 2

Views: 2772

Answers (3)

Str.
Str.

Reputation: 1439

One answer to the let b = problem - it works like this:

let a = 0
let b = if a = 0 then 0 else 1
         (* or whatever value you need in the else branch *)

And then the Map problem: the manual says Map is applicative - that means Stringmap.add returns a new map. You must use a ref to store your map - see this ocaml toplevel protocol:

# module StringMap = Map.Make(String);;

# let mymap = ref StringMap.empty ;;
val mymap : '_a StringMap.t ref = {contents = <abstr>}

# mymap := StringMap.add "high" 1 !mymap;;
- : unit = ()

# StringMap.mem "high" !mymap;;
- : bool = true
# StringMap.mem "nono" !mymap;;
- : bool = false

# StringMap.find "high" !mymap;;
- : int = 1
# StringMap.find "nono" !mymap;;
Exception: Not_found.

Upvotes: 2

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

Yes, if is an expression in OCaml, not a statement. The best way to look at it is that there are no statements in OCaml. Everything is an expression. (Admittedly there are expressions that return (), which are similar to statements.)

You can only have if b then e if the type of e is unit (i.e., if it returns ()).

Note also that you can't just say let v = e, except at the top level of a module. At the top level it defines a global name in the module. In other cases you need to say let v = e1 in e2; the let defines a local symbol v for use in the expression e2.

Upvotes: 3

ezig
ezig

Reputation: 1229

You can only have an if then without else if the then expression evaluates to unit () Otherwise, the expression will not type check. An if without an else is equivalent to writing if x then y else () which can only type check if y is unit.

Check this out for a reference.

(Terminology note: there are no statements in OCaml because everything is an expression, so the term "if statement" doesn't quite apply. I still understood what you meant, but I thought this was worth noting)

Upvotes: 3

Related Questions