mirou
mirou

Reputation: 49

i have weird syntaxe error in ocaml code

i just begin to use Caml and i'm trying to parse a git file: so i used match to filter the lines that begin with diff/@@ and here's what i tried to do: | ["diff"; _; before; after] -> out before; out after;

                 (match  Str.split (Str.regexp "/") file  with 
                     | String.concat "/" [_; path ; dest;file_c ]-> out path; 
                      out dest;
                      out file_c;
                     | _ -> ()
        )

i have a syntxe error here and here : | ["@@"; lines_deleted; lines_added; _] -> out lines_deleted; out lines_added;

                   let   nb_lines_deleted = String.sub lines_deleted 2 ((String.length lines_deleted)-1) in
                     let  nb_lines_added = String.sub lines_added 2 ((String.length lines_added)-1) in
        ( match ( Str.split (Str.regexp ",") lines_deleted ) with 
                    | [_;  nb_lines_deleted;_; nb_lines_added] -> out nb_lines_deleted;
               out nb_lines_added;
                    | _ -> ()
                  )
           | _ -> ()

and i don't understand why! i tried diffrent things but nothing worked!

Upvotes: 1

Views: 68

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

As Thomash says, the different alternatives of a match expression are built up from constants and data constructors (and names representing "wild cards" in essence). But you're trying to use a general expression there.

The following is analogous to what you're trying to do:

match x with
| a * b + 7 -> "case 1" (* Not a valid OCaml match *)
| _ -> "case 2"

The way a match really works is:

match x with
| 1 -> "case 1"
| 2 -> "case 2"
| _ -> "case N"

You need to use an if instead of a match:

if x = a * b + 7 then "case 1" else "case 2"

Update:

Here's how a match looks, roughly speaking:

match <<any expression>> with
| <<pattern>> -> <<expression>>
| <<pattern>> -> <<expression>

So you can have any expression between match and with. It's reasonable to have Str.split there. Patterns, on the other hand, are restricted. In essence they are like complicated constant values. They can also contain "wild-card" names that are defined by the match, i.e., they get set to the part of the value that matches at that point. But you could never have Str.split or String.concat in a pattern. For basic knowledge like this, it would be best to read a book or tutorial about OCaml.

Upvotes: 3

Thomash
Thomash

Reputation: 6379

You seem to use match with for comparisons. For that you you must use if then else.

Upvotes: 0

Related Questions