let () = Random.self_init();;
let _ = Random.self_init ();;
│- : unit = ()
It seems “let ()” returns nothing ?
Sincerely!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
letis the keyword used to define new variables, like in the following construct:For instance
assigns the value
2to the namea. (Note this is not a way to assign a value to an already existing variable, but this is another topic).But the pattern to the left of the
=sign can be more than just a name. For instancedefines both
aandb, to be respectively42and"foo".Of course, the types on both sides must match.
Which is the case here: both sides are of type
int * string.The expressions to the right of the
=sign can also be elaborated, for instancedefines
fooas the string"aabaaaaaaa". (As a side note, it also ensures thattempis local to this code snippet).Now, let’s use both: on the left, a pattern matching values of type
unit, and on the right, an expression of typeunit:Which explains the
let () =construct.Now, about the
let _, one simply needs to know that_can be used in a pattern as a wildcard: it matches values of any type and does not bind any name. For instancedefines
aas42, and discards the value"foo"._means “I know there is something here and I explicitly say I will not use it, so I don’t name it”. Here_was used to match values of typestring, but it can match value of any type, likeint * string:which does not define any variable and is not very useful. Such constructs are useful when the right hand side has side effects, like this:
which explains the second part of the question.
Practical purposes
Both are used and it’s rather a matter of taste whether to use one or the other.
let () =is slightly safer as it has the compiler check that the right hand side is of typeunit.A value of any other type than unit is often a bug.
let _ =is slightly shorter (I’ve seen this argument). (Note that with an editor that automatically closes parenthesizes, the number of keystrokes is the same 😉