Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this F# / OCaml "match" expression compile?

This code compiles just fine in F# as well as OCaml:

let testmatch k =
    match k with
    | jqk3jtl23jtlk123 -> true

I've tested in both FSI and utop. It always returns true.

The jqk3jtl23jtlk123 is totally random, and its type is inferred as 'a. Even if I constrain k with a datatype (e.g. let testmatch (k: int) =) it compiles (though obviously constraining testmatch's type to int -> bool instead of 'a -> bool.

Could someone please explain what's going on? Specifically:

  • why does the compiler accept a totally random literal jqk3jtl23jtlk123?
  • why do I not get an inexhaustive match warning?
  • what is the match actually doing?
like image 317
Prashant Vaibhav Avatar asked Sep 15 '17 14:09

Prashant Vaibhav


People also ask

Why is it f in the chat?

In the years after the release of Advanced Warfare, users began typing a singular "F" in chat windows on websites such as Twitch to convey condolences or a sense of sorrow when reacting to any unfortunate news on the internet, leading streamers and others to refer to this with the phrase "F in the chat".

What does f * * * * * * mean?

verb (used with object) Slang: Vulgar. to have sexual intercourse with. to treat unfairly or harshly (usually followed by over). verb (used without object) Slang: Vulgar.

What does f mean in Snapchat?

Summary of Key Points. "Drooling" is the most common definition for :F on Snapchat, WhatsApp, Facebook, Twitter, Instagram, and TikTok. :F. Definition: Drooling.


2 Answers

In this case, the "literal" jqk3jtl23jtlk123 is a valid variable name, and so what the pattern to the left of -> describes is the same as if you wrote let jqk3jtl23jtlk123 = k. Since this accepts any value of k, and does not constrain its type because binding works for all types, the inferred type is 'a, the most generic value the type system can represent.

If you turn the literal into something that is not a valid identifier, for example beginning with a digit, it will fail to compile.

If you wrap the literal in quotes, it will be interpreted as a string value literal, you should get the inexhaustive match warning, and it will constrain k's type to string.

like image 168
Honza Brestan Avatar answered Oct 25 '22 00:10

Honza Brestan


This is a wildcard pattern, which names whatever k is equal to. This is equivalent to

let testmatch k =
    let jqk3jtl23jtlk123 = k in
    true
like image 29
Étienne Millon Avatar answered Oct 25 '22 00:10

Étienne Millon