How is float_of_int -3 evaluated? - ocaml

# float_of_int -3;;
Error: This expression has type int -> float
but an expression was expected of type int
I thought function application has the highest precedence, so float_of_int -3 is equal to float_of_int (-3). Why do I need to put the parentheses explicitly there to suppress the error?

Exactly because of this reason, that function application is having higher precedence than infix operators, you have to add parenthesis.
In other words, function application is greedy and it will consume all terms until it reaches an infix operator, e.g.,
f x y z + g p q r
is parsed as (f x y z) + (g p q r).
The same is with your example,
float_of_int - 3
is parsed as
(float_of_int) - (3)
Another option for you would be to use a special prefix operator ~-, e.g.,
float_of_int ~-1
which has higher precedence (binds tighter) than the function application.

Related

Optional parameter at the end effects the label parameter before

Why does let f ~x ?(y = 1) = x - y;; make the label for argument x become necessary? In other words, when I tried to evaluate f 3 ~y:2;;, I received this error:
Error: The function applied to this argument has type x:int -> int
This argument cannot be applied without label
What's the reason behind such design?
It is not necessary to label the argument x:
let g = f 0
works and returns a function g of type ?y:int -> int.
To understand this behaviour, it is best to remember that the generic rule is that
labels are mandatory when applying a function.
However, there is a specific rule for total application: if a function is applied to as many non-optional arguments as possible, then labels can be omitted.
A typical example would be
let f ~a ~b c d ~e f ~g = a + b + c + d + e + f + g
let x = f 1 2 3 4 5 6 7
Going back to your case, your function f takes at most one non-optional argument. It is thus considered as totally applied when applied to exactly one argument.
Another important point is that optional arguments are only send to the function once a subsequent positional argument has been sent. This explains why the variable g is still a function: no positional arguments were provided to f thus the optional argument ?y was never sent to f.
Applied to more complex example
let f ~a ?(b=0) c ~d e ~f ~g ?(h=0) = a + b + c + d +e + f + g + h
(* there are 8 arguments, 2 optional *)
(* g is applied to the full 6 non-optional arguments, thus total *)
let g = f 1 3 4 5 6 7
the type of g is ?h:int -> 0. Indeed, the application is total, thus all non-optional arguments have been provided. Then, the first optional argument ?b was followed by a positional argument. It was then provided to the function. However, the last optional argument ?h has not been yet triggered and is still here.
This behavior implies that optional argument are only useful if there is at least one positional argument after them, as advised by the compiler itself:
let f ~x ?(y=0) = x + y;;
Line 1, characters 11-14:
Warning 16: this optional argument cannot be erased.

Why do i get error when i use x+ but not when +x in this code?

x = 2
if x == 2:
print x
else:
x +
i get error like
print x +
^
SyntaxError: invalid syntax
+x calls __pos__(self) and is therefore a valid python statement; x + y is an expression that needs two operands (see binary arithmetic expressions); x + is invalid.
This is the unary operator +, which is like writing -x but doesn't really do anything. See this article for more information.
In +x, + is an operator that works on a single number, such as -x and ~x. You can refer the bottom table on https://docs.python.org/2/reference/expressions.html.
However, in x +, + is an operator for two numbers. In your code, the second number is not provided, so you got an error.
You can check this answer
What's the purpose of the + (pos) unary operator in Python? for why we need +x in Python.

Error when passing negative integer to a function in OCaml

If I define a function in OCaml, for example let f x = x + 1;; and then I try to call it passing a negative number
f -1;; it gives to me the following error
Error: This expression has type int -> int
but an expression was expected of type int
Why this error occurs?
Basically, it comes from the precedence of the parser. The compiler believes that f -1 means you want to subtract f by 1. It has been complained about for ages now.
Typing in f (-1) or f ~-1 will solve your problem (the later using the "explicitly unary minus").
UPDATE:
As stated in the OCaml manual:
Unary negation. You can also write - e instead of ~- e.
Basically, - can be used both as a binary operator 4 - 1 and a unary operator -1. But, as in your case, there can be confusion: f - 1 is "f minus one" and not "f applied to minus one". So the ~- operator was added to have a non-confusing unary minus as well.
Note that the spaces are not significant here, and that won't change because a lot of already existing code may contain operations without space.

Why are VB.NET and C++ giving different results for same expression?

Consider the following snippets:
C++:
#include <iostream>
using namespace std;
int main()
{
int x = 10, y = 20;
y = x + (x=y)*0;
cout << y;
return 0;
}
which gives a result of 20, because the value of y is assigned to x since the bracket is executed first according to the Operator Precedence Table.
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As Integer = 10
Dim y As Integer = 20
y = x + (x = y) * 0
MsgBox(y)
End Sub
which instead gives a result of 10.
What is the reason for this difference?
What is the order of execution of operators in VB.NET?
Unlike in C++, VB.NET's = is not always an assignment. It can also be the equality comparison operator (== in C++) if it appears inside an expression. Therefore your two expressions are not the same. They are not even equivalent. The VB.NET code does not do what you might think it does.
First to your C++ code: Like you're saying, the assignment x=y happens first; thus your code is roughly equivalent to this: (It seems that was incorrect; see Jens' answer.) Since you end up with y being 20, it is likely that your C++ compiler evaluated your code as if you had written this:
int x = 10, y = 20;
x = y;
y = x + x*0; // which is equivalent to `y = 20 + 20*0;`, or `y = 20 + 0;`, or `y = 20;`
In VB.NET however, because the = in your subexpression (x=y) is not actually interpreted as an assignment, but as a comparison, the code is equivalent to this:
Dim x As Integer = 10
Dim y As Integer = 20
y = 10 + False*0 ' which is equivalent to `y = 10 + 0*0`, or `y = 10` '
Here, operator precedence doesn't even come into play, but an implicit type conversion of the boolean value False to numeric 0.
(Just in case you were wondering: In VB.NET, assignment inside an expression is impossible. Assignments must always be full statements of their own, they cannot happen "inline". Otherwise it would be impossible to tell whether a = inside an expression meant assignment or comparison, since the same operator is used for both.)
Your C++ snippet is undefined behavior. There is no sequence point between using x as the first argument and assigning y to x, so the compiler can evaluate the sub-expressions in any order. Both
First evaluate the left side: y = 10 + (x=y) * 0 -> y = 10 + (x=20) * 0 -> y = 10 + 20*0
First evaluate the right side: y = x + (x=20) * 0 -> y = 20 + 20 * 0
It is also generally a very bad style to put assignments inside expressions.
This answer was intended as a comment, but its length quickly exceeded the limit. Sorry :)
You are confusing operator precedence with evaluation order. (This is a very common phenomenon, so don't feel bad). Let me try to explain with a simpler example involving more familiar operators:
If you have an expression like a + b * c then yes, the multiplication will always happen before the addition, because the * operator binds tighter than + operator. So far so good? The important point is that C++ is allowed to evaluate the operands a, b and c in any order it pleases. If one of those operands has a side effect which affects another operand, this is bad for two reasons:
It may cause undefined behavior (which in your code is indeed the case), and more importantly
It is guaranteed to give future readers of your code serious headaches. So please don't do it!
By the way, Java will always evaluate a first, then b, then c, "despite" the fact that multiplication happens before addition. The pseudo-bytecode will look like push a; push b; push c; mul; add;
(You did not ask about Java, but I wanted to mention Java to give an example where evaluating a is not only feasible, but guaranteed by the language specification. C# behaves the same way here.)

converting context free grammar into regular expression

I am currently going over CFG and saw the answer and I am not sure how they got it. How did they get it to convert into Regular Expression from CFG here?
S -> aS|bX|a
X -> aX|bY|a
Y -> aY|a
answer:
R.E -> (a*(a+ba*a+ba*ba*a))
You should learn the basic rules that I have written in my answer "constructing an equivalent regular grammar from a regular expression", those rules will help you in converting "a regular expression into right or left liner grammar" or "a right or left liner grammar into regular expression" - both.
Though, more than one regular expressions (and grammars/automata) can be possible for a language. Below, I have tried to explain how to find regular expression given in answer for the question in your textbook. Read each step precisely and linked answer(s) so that you can learn approaches to solve such questions yourself next time.
At first step, to answering such question you should be clear "what does language this grammar generate?" (similarly, if you have an automata then try to understand language represented by that automata).
As I said in linked answer, grammar rules like: S → eS | e are corresponding to "plus clouser" and generates strings e+. Similarly, you have three pairs of such rules to generate a+ in your grammar.
S → aS | a
X → aX | a
Y → aY | a
(Note: a+ can also be written as a*a or aa* – describes one or more 'a'.)
Also notice in grammar, you do not have any "null production" e.g. A → ∧, so non-of the variable S, X or Y are nullable, that implies empty string is not a member of language of grammar, as: ε ∉ L(G).
If you notice start-variable's S productions rules:
S → aS | bX | a
Then it is very clear that strings ω in language can either start with symbol 'a' or with 'b' (as you have two choices to apply S productions either (1) S → aS | a that gives 'a' as the first symbol in ω, or (2) S → bX that use to produce strings those start with symbol 'b').
Now, what are the possible minimum length strings ω in L(G)? – minimum length string is "a" that is possible using production rule: S → a.
Next note that "b" ∉ L(G) because if you apples S → bX then later on you have to replace X in sentential form bX using some of X's production rules, and as we know X is also not nullable hence there would be always some symbol(s) after 'b' – in other words sentimental from bX derives &mid;ω&mid; &geq; 2.
Form above discussion, it is very clear that using S production rules you can generate sentential forms either a*a or a*bX, in two steps:
For a* use S → aS repeatedly that will give S &zigrarr; a*S (symbol &zigrarr; means more than one steps)
Replace S in rhs of S &zigrarr; a*S to get either by a*a or a*bX
Also, "a*a or a*bX" can be written as S &zigrarr; a*(a + bX) or S &zigrarr; (a*(a + bX)) if you like to parenthesizes complete expression✎.
Now compare production rules of S and X both are the same! So as I shown above for S, you can also describe for X that it can use to generate sentential forms X &zigrarr; (a*(a + bY)).
To derive the regular expressions given in answer replace X by (a*(a + bY)) in S &zigrarr; a*(a + bX), you will get:
S &zigrarr; a*(a + b X )
S &zigrarr; a*(a + b (a*(a + bY)) )
And now, last Y production rules are comparatively very simple - just use to create "plus clouser" a+ (or a*a).
So let's replace Y also in S derived sentential form.
S &zigrarr; a*(a + b(a*(a + bY)))
&zigrarr; a*(a + b(a*(a + ba*a)))
Simplify it, apply distribution low twice to remove inner parenthesis and concatenate regular expressions – P(Q + R) can be written as PQ + PR.✞
&zigrarr; a*(a + b(a*(a + ba*a)))
&zigrarr; a*(a + b(a*a + a*ba*a))
&zigrarr; a*(a + ba*a + ba*ba*a)
✎ : &plus; in regular expression in formal languages use in two syntax (i) &plus; as binary operator means – "union operation" (ii) &plus; as unary superscript operator means – "plus clouser"
✎ : In regex in programming languages + is only uses for "plus clouser"
✞ : In regex we use &mid; symbol for union, but that is not exactly a union operator. In union (A ∪ B) is same as (B ∪ A) but in regex (A &mid; B) may not equals to (B &mid; A)
What you can observe from the question is that the grammar apart from being a CFG is also right linear. So you can construct an finite automata for this right linear grammar. Now that you have the finite automata constructed their exists a regular expression with the same language and the conversion can be done using the steps given in this site.