Matching parameters to FSharp parameters. Why is a declaration assigned instead?

I am looking at FSharp. I am currently reading this resource: http://fsharpforfunandprofit.com/

Since I am learning something completely new, including new thinking, I am wary of something that makes no sense to me.

let f1 name =                        // pass in single parameter   
    let {first=f; last=l} = name     // extract in body of function 
    printfn "first=%s; last=%s" f l

      

Why do "f" and "l" on the right side match the corresponding "=" signs? Isn't that the moment they are announced? I believe I know what the string does (it retrieves the "first" and "last" properties from the "name" entry). But I can't figure out the reasons for this syntactic choice, which makes me suspect that I don't quite understand what's going on here.

+3


source to share


1 answer


The part of the syntax between let

and =

is called a pattern. As mentioned in the comments, the template reflects the syntax that you use when creating a post.

In general, the idea with a template is that you specify a portion of the objects that you know (here, the record field names) and in places that differ (the field values), you can either put the variable name (in this case, the pattern matching links variable), or you can write _

to ignore the value in that part of the object.

Here are some examples of creating values:



let opt = Some(42)                              // Option type containing int
let rcd = { First = "Tomas"; Last = "Hidden" }  // Record from your example
let tup = 42, "Hello"                           // Tuple with int and string

      

In all cases, you can reflect the syntax in the template:

let (Some(num)) = opt         // This gives warning, because 'opt' could also be None
let { First = n; Last = _ }   // Here, we explicitly ignore the last name using '_'
let _, str = tup              // Ignore first component of the tuple, but get the 2nd

      

+2


source







All Articles