简体   繁体   中英

Operator :: OCaml

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.

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM