What is the meaning of this one line F# snippet
let x x = x + 2 in x 2;;
It is valid and just return 4.
But what is it?? is x a function? is it also a parameter? also x seems to be calling itself (x 2) but its not marked with "rec".
Can anyone explain?
F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces.
The f in f-strings may as well stand for “fast.” f-strings are faster than both %-formatting and str.format() . As you already saw, f-strings are expressions evaluated at runtime rather than constant values.
Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string. For example, "This" is a string whereas f"This" is an f-String.
Essentially, you have three options; The first is to define a new line as a string variable and reference that variable in f-string curly braces. The second workaround is to use os. linesep that returns the new line character and the final approach is to use chr(10) that corresponds to the Unicode new line character.
So lets try to understand what happens.
let x x
defines a function called x
which takes an argument of x
.
`let x x = x + 2`
means you have a function x
which takes an argument also called x
and returns x+2
The final part in x 2
calls the function with an argument of 2.
So the function can be written as
let f x = x + 2
f 2
which obviously returns 4.
The 'in' means that it's not using light syntax. Basically, the in
means that the prior binding is defined for the following expression. Since the in
keyword means that the binding of x is valid for the following expression, another way of writing it would be to replace x
with the value of the binding like so:
(fun x -> x + 2) 2
I think it's important to be aware of the fact that all bindings work in this way, i.e. bindings are a way of writing expressions in a more understandable way.
If you look here, you can learn more about the more OCaml like syntax F# has available if you have #light off
specified (on
is the default).
let x x = x + 2 in x 2;;
Disambiguate the variables by renaming the outer x
to f
:
let f x = x + 2 in f 2;;
Indent:
let f x =
x + 2
f 2
So it defined a function that adds two and applies it to two to get four.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With