OCaml Analysis Function

This is a function from the parser module. I'm having trouble understanding one line of code

let rec e1 tokens = match tokens with Tokenizer.IfTok :: tokens1 -> let (testAST, tokens2) = e1 tokens1 in (match tokens2 with Tokenizer.ThenTok :: tokens3 -> let (thenAST, tokens4) = e1 tokens3 in (match tokens4 with Tokenizer.ElseTok :: tokens5 -> let (elseAST, tokens6) = e1 tokens5 in (If(testAST, thenAST, elseAST), tokens6) | _ -> raise (Syntax ("e1: missing else."))) | _ -> raise (Syntax ("e1: missing then."))) | _ -> e2 tokens and e2 tokens = ........ 

I do not know how this line works

 let (testAST, tokens2) = e1 tokens1 in 

I know that it declares a local variable, which is a tuple, but where did the value come from (testAST, tokens2)? This seems to have nothing to do with tokens or tokens1. Also does this line only declare a tuple or also call a function? Thanks!

+4
source share
2 answers

Yes, this line declares two variables and calls the function e1 , binding the variables to the result of the function call.

This method of binding variables is called pattern matching. It is based on information about the return type of the e1 function - the compiler knows that it returns a tuple, and then it can be decomposed into parts, and these parts are bound to two new variables testAST and tokens2 . This is one of the most powerful FP features that allows you to write much more readable, flexible, and shorter code.

It can also be done (agreed) on everything if the structure of this object (template) is known to the compiler (for example, case classes in Scala, tuples and lists in Haskell, entries in Erlang, etc.). Also, pattern matching can be used to ignore some parts of the structure that are not relevant to the conditions (for example, in Haskell, if you want to select the second element in three tuples, just do selectSecond (_, a, _) = a , where _ is special character to ignore values).

+3
source

It calls a function called e1 . In fact, this is the very function in which it appears; that is, it is a recursive call to e1 . The function returns a pair (2-tuple).

This looks like a fairly standard recursive descent analysis .

0
source

Source: https://habr.com/ru/post/1442868/


All Articles