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.
Related
I'm an OCaml beginner using OCaml 4.12.0 on MacOS. This let expression:
let gg x y = (x -. y) < 5.0
at the toplevel results in:
Error: This expression has type float but an expression was expected of type
int
Explicitly adding type information, etc., did not fix the problem. In frustration, I visited the online REPL TryOCaml, and the expression was accepted without error, returning the type signature of:
val f : float -> float -> bool = <fun>
as expected. But I'd like utop to work on the Mac - what am I missing?
Very possibly you're using a library that overrides the built-in meaning of < in OCaml. Some people (not me) think the polymorphic comparison operators are a problem.
One problem with this (IMHO) is that it causes confusing results like this.
For example, the Jane Street Base library is documented as overriding the polymorphic comparison operators: https://ocaml.janestreet.com/ocaml-core/latest/doc/base/index.html
When you use Base (or Core, or Core_kernel and other Janestreet standard libraries) the comparison operator and its friends (like various equality operators) work only on values of type int. For all other values you have to use specialized comparison operators provided by the module that implements that type, e.g., to compare two floats,
Float.(3.14 < 4.14)
to compare strings,
String.("hello" <> "world")
And, using your example,
let gg x y = Float.(x -. y < 5.0)
or even
let gg x y = Float.(x - y < 5.0)
Notice that we don't need to use the ugly -. operators anymore and can use - (and other arithmetic operators) as they are all defined specifically for float in module Float.
Besides, the notation Foo.(<expr>) is a short-hand for let open Foo in <expr> and is called local open.
# 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.
#include <iostream>
using namespace std;
int main()
{
int arr[3] = { 10, 20, 30 };
cout << arr[-2] << endl;
cout << -2[arr] << endl;
return 0;
}
Output:
4196160
-30
Here arr[-2] is out of range and invalid, causing undefined behavior.
But -2[arr] evaluates to -30. Why?
Isn't arr[-2] equivalent to -2[arr]?
-2[arr] is parsed as -(2[arr]). In C (and in C++, ignoring overloading), the definition of X[Y] is *(X+Y) (see more discussion of this in this question), which means that 2[arr] is equal to arr[2].
The compiler parses this expression
-2
like
unary_minus decimal_integer_literal
That is definitions of integer literals do not include signs.
In turn the expression
2[arr]
is parsed by the compiler as a postfix expression.
Postfix expressions have higher precedence than unary expressions. Thus this expression
-2[arr]
is equivalent to
- ( 2[arr] )
So the unary minus is applied to the lvalue returned by the postfix expression 2[arr].
On the other hand if you wrote
int n = -2;
and then
n[arr]
then this expression would be equivalent to
arr[-2]
-2[arr] is equivalent to -(2[arr]), which is equivalent to -arr[2]. However, (-2)[arr] is equivalent to arr[-2].
This is because E1[E2] is identical to (*((E1)+(E2)))
The underlying problem is with operator precedence. In C++ the [], ie the Subscript operator hold more precedence (somewhat akin to preferance) than the - unary_minus operator.
So when one writes,
arr[-2]
The compiler first executes arr[] then - , but the unary_minus is enclosed within the bounds of the [-2] so the expression is decomposed together.
In the,
-2[arr]
The same thing happens but, the compiler executes 2[] first the n the - operator so it ends up being
-(2[arr]) not (-2)[arr]
Your understanding of the concept that,
arr[i] i[arr] and *(i+arr) are all the same is correct. They are all equivalent expressions.
If you want to write in that way, write it as (-2)[arr]. You will get the same value for sure.
Check this out for future referance :http://en.cppreference.com/w/cpp/language/operator_precedence
I am trying to code a C++ app that will be able to calculate a mathematical expression. Doing so I must convert a infix expression into a postfix expression and then calculate the value.
Before I can start with the conversion of the infix expression into a postfix expression and to calculate it I must first instantiate the x and y by giving it values. My question is this. How can I search for x and y in the 'expr' string in the instantiateVariable function and assign the values to it (as it is done in the main.cpp) when its found?
I'm quite sure one can use a for loop but how should I be doing it? Any help will be appreciated.
main.cpp
int main()
{
Expression expr("x + y + sqrt 25 - 3");
expr.instantiateVariable('x',5);//Set x = 5
expr.instantiateVariable('y',3);//Set y = 3
/*
The output of the following statement should be:
Answer: 10
*/
cout<<"Answer: "<<expr.evaluate()<<endl;
}
and in my header folder I have the following:
Expression.h
class Expression
{
public:
Expression(string expr);
~Expression();
void instantiateVariable(char name, int value);
int evaluate();
};
I would go for a naive Shunthing-yard. The principle is easy:
Reach each operand and put them on a queue
Every time you encounter an operator put it on a stack
If the operator on top of the stack has a higher precedence pop it and add it to the queue (it needs to be calculated first)
Continue until the end of the expression and then pop everything to the queue
supporting parenthesis is also easy with this method.
Some parsing is obviously required (a tokenization to be precise) but this is going to be pretty straightforward.
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 ∣ω∣ ≥ 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 ⇝ a*S (symbol ⇝ means more than one steps)
Replace S in rhs of S ⇝ a*S to get either by a*a or a*bX
Also, "a*a or a*bX" can be written as S ⇝ a*(a + bX) or S ⇝ (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 ⇝ (a*(a + bY)).
To derive the regular expressions given in answer replace X by (a*(a + bY)) in S ⇝ a*(a + bX), you will get:
S ⇝ a*(a + b X )
S ⇝ 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 ⇝ a*(a + b(a*(a + bY)))
⇝ 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.✞
⇝ a*(a + b(a*(a + ba*a)))
⇝ a*(a + b(a*a + a*ba*a))
⇝ a*(a + ba*a + ba*ba*a)
✎ : + in regular expression in formal languages use in two syntax (i) + as binary operator means – "union operation" (ii) + as unary superscript operator means – "plus clouser"
✎ : In regex in programming languages + is only uses for "plus clouser"
✞ : In regex we use ∣ symbol for union, but that is not exactly a union operator. In union (A ∪ B) is same as (B ∪ A) but in regex (A ∣ B) may not equals to (B ∣ 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.