1

I am a beginner in OCaml and trying to build a parser, I want to have a list that stores all the methods in my class. This is one part that I have in my .mly file.

init_method_list: 
    { [] }
    | method_list method_decl { List.rev($1) }
;

method_list:
    method_decl { [ $1 ] }
    | method_list method_decl { $2 :: $1 }
;

Can anyone explain exactly what's going on here? Especially the :: operation. Been googling around but couldn't find the operator in the docs.

I get that the list can be empty, or we make right recursive calls to fill it up with all the methods in class. method_decl just looks for the match of the specific token combinations that represents a method.

novalain
  • 2,181
  • 19
  • 36

2 Answers2

4

As I said in my comment, the operator :: is use to concatenate an element of type 'a to a list of type 'a list. A little example :

1 :: [2;3] produces the list [1;2;3] so yes it prepend the element to the front of the list.

alifirat
  • 2,899
  • 1
  • 17
  • 33
  • 1
    The `::` is not really an operator but rather a syntactic notation – this why it is allowed to appear in matching patterns while operators are not. – Michaël Le Barbier Apr 28 '16 at 12:44
0

As everyone else said, :: concatenates an element onto a list of the same type. As just an extra aside, if you need to concatenate two lists, you can use the @ symbol, for example:

[1;2;3]@[4] will give the list [1;2;3;4]

issharp
  • 310
  • 6
  • 22