I am reading f# code and I am confused by the syntax. A Parser type is introduced as follows:
type Parser<'r> = Parser of (char list -> ('r*char list) list)
This is evaluated by the interpreter as:
type Parser<'r> = | Parser of (char list -> ('r * char list) list)
which makes sense to me. Then, a new line of code is introduced: ‘A parser function also needs to be applied so we define a partial function for that:’, and the code that follows:
let parse (Parser p) = p
and the interpreter output is:
Parser<'a> -> (char list -> ('a * char list) list)
I am surprised this is even valid syntax. What is it and why is it needed?
Many thanks
In general
let fpattern=bodyis equivalent to
let f = function|pattern->bodyor, even more verbosely,
let f x =match x with|pattern->bodyThis allows you to avoid introducing a new identifier which is immediately destructured and then never used again.
In this particular example, that means that
parseis equivalent to:Since there is only a single case in the
Parsertype, this destructuring will always succeed.