Syntax error in ocaml - ocaml

Why does the following code has a syntax error? I did not find out why.
let rec revStr stringa k e =
if k = e then ""
else (string_of_char stringa.[e])^
(revStr stringa (e-1) k);;
string a, k, e are the input and it should give in output the sub.string from integer e to integer k.

There is no syntax error in this code. When I try it I get "Unbound value: string_of_char" which is a type error. Type errors appear after syntax errors, because typing occurs after parsing.
My guess is that you have a syntax error before this function, such as a forgotten semi-colon or a forgotten "in". Those kinds of errors are often detected much later.

In addition to what cygin points out (parameters seem reversed), revStr calls itself with a smaller value for e. But your description sounds like e is supposed to be less than or equal k. So then wouldn't you want to pass a larger value for e? Otherwise I don't see why you would ever reach k.
As a side comment, I wonder why a substring function is named revStr.

Related

Ocaml, syntax error but i don't know where, can somoene help me?

This is my code, i need some help with it. Compiler give me some syntax error that i can't fix and i can't identify!
let n = read_int();
let schroder n =
let pointer = ref 0 in
for i = 1 to n-2 do
pointer := !pointer + (schroder i * schroder n-i-1)
done;
schroder n = 3 * schroder n-1 + !pointer
!schroder n
It looks to me like your main problem is in the first line. The semicolon in OCaml is an operator with a left and right operand. This means that the semicolon on your first line will combine the expression before it (read_int ()) and the one after it (let schroder ...) into one expression. But when let occurs inside a larger expression, it requires an in. You don't have an in to match let schroder .... That, I believe, is your syntax error.
If you want schroder to be defined at the outermost level (which I think you do), you should remove the semicolon on the first line.
When I make this change in your code, I no longer get a syntax error. Instead I get an error for which the compiler has a pretty good suggested fix.
There are still some more errors, but I hope this helps with the initial syntax error.

Absolute value function Ocaml

I'm taking a look to this programming language "Ocaml" and I have some troubles because I read the official ocaml documentation but I don't uderstand how to use :
";" and ";;" and "in" specially inside the definition of functions.
This is my code :
let abs_val value : int -> int =
let abs_ret = ref 0 ;
if value >= 0
then abs_ret := value
else abs_ret := -value ;
let return : int = abs_ret
;;
print_int abs_val -12
Compiled with "ocamlc" it said :
File "first_program.ml", line 7, characters 2-4:
7 | ;;
^^
Error: Syntax error
And it sounds so weird for me because official ocaml's doc says that when function definition ends I must use ";;".
I noticed that after the definition of abs_val VisualStudio Code ,when I go on a newline, put automatically the cursor to 2 spaces on the right, not at the beginning of the line.
I'm new in ocaml so I don't know if this is common or not but for me sounds like if something is missing, and probably it is :)
P.S. : I know that an abs function already exists but I'm doing this to learn.
Update :
let abs_val value =
let abs_ret = ref 0 in
if value >= 0
then abs_ret := value
else abs_ret := -value in
let return : int = abs_ret;
;;
print_int abs_val -12
Am I closer right?
Sometimes it happens the syntax error is not here but above. Did you closed your previous function with ;; ? Also, what is this return ? Use the functional paradigm of the language. You use variables and references and force the type checking. I'm not sure how do you want to use this code but in a general way, try to let OCaml determine the type of your functions rather than telling the compiler what is the signature. Plus, your code shouldn't be using that much references. For instance the following :
let abs_val value =
if value < 0 then
-value
else
value
Will work perfectly and not mess up things with reference. If you wish to use references, I suggest you learn more about the functional paradigm of OCaml before going deeper into its imperative possibilities.
Your syntax error is a result of having let with no matching in.
This is a very common error when learning OCaml syntax. There are two separate uses of let in OCaml. At the top level of a module, you use let to define a symbol (a function or a value) that is one of the elements of the module. So in the following:
module M = struct
let f x = x * 2
end
The let defines a function named M.f.
Similarly your code uses let this way to define abs_val.
In other cases (not at the top level of a module), let is used only as part of the let ... in expression that looks like this:
let v = exp1 in exp2
This essentially defines a local variable v with the value exp1 that can be used in the body of exp2.
All your other uses of let (except the initial definition of abs_val) are of this second kind. However, none of them have in, so they are all syntactically incorrect.
You need to fix up these problems before you can make progress with this function. You can fix the first one, for example, by changing the first semicolon (;) to in.
As #SDAChess points out, you have a second problem with the return value of your function. There is no special return keyword in OCaml that's used to return the value of a function. A function in OCaml is just a set of nested function calls, and the value of the function is the value returned by the outermost call.

Compare real list in sml

For the next code I'm getting an error:
fun epoly(L:real list, x:real)=
= if L = [] then 0.0 else (epoly(tl(L:real list), x:real));;
Error:
stdIn:42.1-42.57 Error: operator and operand don't agree [equality type required]
operator domain: ''Z * ''Z
operand: real list * 'Y list
in expression:
L = nil
Since you're not actually asking a question, it is a little unclear what your intent is. Presumably this is attempted code that doesn't work and the accompanying error message, and the implicit question is "Why doesn't this code work? What am I doing wrong, and what can I do to improve it?" But really that's guesswork, and those are lazy questions, too.
Here's how your post could look like if my assumptions above are correct and you want positive feedback in the future:
I am trying to write a function that evaluates a polynomial with real coefficients L for the variable x.
It looks like:
fun epoly (L : real list, x : real) =
if L = [] then 0.0 else epoly(tl L, x)
Unfortunately I am getting a type error that I don't understand:
stdIn:1.35-1.91 Error: operator and operand don't agree [equality type required]
operator domain: ''Z * ''Z
operand: real list * 'Y list
in expression:
L = nil
What does this error mean, and if this is not the right way to evaluate a polynomial, then what would another way to accomplish the same thing look like?
The take-aways:
Write what your problem is, don't let others assume what your problem is. Making a question easily understood makes people want to answer your question, and describing your problem in words tells what you think is the problem, so that people don't try and answer the wrong question. In this case, your question could have been "Under what version of the Standard ML specification were reals removed as an eqtype?" and a sufficient answer would have been '97. But would you have been happy about that answer?
Once you know how to ask the right question, you can also better google around (e.g. search for: evaluate polynomial "standard ml"|sml) and find that there exists code from which you can let yourself inspire: here, here, here.
Format your code nicely and make sure it works. Use StackOverflow's Markdown to format your code nicely. The code that you posted contains artifacts from the interactive REPL (an extra =), so anyone who copy-pastes it into a REPL will get an error, will have to figure out where it occurred, fix it, and then start to think about what could be the problem, since you didn't say. A good rule is to test that the code you posted works by copy-pasting it once you've asked the question. One can easily forget to include a non-standard function.
An answer, assuming my rendition of your "question" somewhat lines up with your intent:
When you do if L = [] ... then you're using equality for lists of reals, which in turn relies on equality for reals, but reals can't be compared for equality. See the Q&A "Why can't I compare reals in Standard ML?" You can test if a list of reals is empty without comparing reals by doing e.g.:
fun epoly (L, x) =
if null L then 0.0 else epoly (tl L, x)
This is because the standard library function null uses pattern matching on lists but does not address the list's elements, whereas = assumes that elements may have to be compared. Even though that never happens in practice in the example L = [], this is still an error in the type system.
If you were comparing reals for equality, consider using an epsilon test. Besides that, consider using pattern matching instead of hd and tl because those functions can fail and crash because they're partial:
fun epoly ([], x) = 0.0
| epoly (c::cs, x) = epoly (cs, x)
All this function does is throw away its second argument x, traverse its first argument, c::cs, and do nothing with each coefficient c. Presumably, in order to evaluate a polynomial, you must do something to coefficient c and x before doing the same thing recursively on the remaining coefficients cs and x, and then somehow compose those.

What does this mean in Opencv Documentation?

Im trying to understand goodFeaturesToTrack and in the documention at this link:
http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=goodf#goodfeaturestotrack
it says "
Note
If the function is called with different values A and B of the parameter qualityLevel , and A > {B}, the vector of returned corners with qualityLevel=A will be the prefix of the output vector with qualityLevel=B . "
is A > {B} just a is greater than b or does it mean something else
I think, there is a typo in the documentation, and B should not be in curly brackets. Probably, it was an intent to make this letter be of different font.
Since the qualityLevel parameter is double, and from RTFS (reading the fine sources :) ) I conclude that this text says the following.
If you call this function several times, decreasing qualityLevel step by step, then this function will return the same results, just truncating them somewhere at the end.
In other words, if you compare results from two such calls, you'll see the same elements in the beginning and different amount of the results.

Get Index of Num Array in Haskell

I would need to get the position of an element in may array of type Array Int Int. I found the method elemIndex or find to get the position. My problem is, that I don't need the prefix Just 5 for example. So how I only get the number 5 in my example?
The principle
To safely extract a value from a Maybe a value, you can either use pattern matching, like so:
case elemIndex 'C' list of
Just n -> "You can find C at position " ++ show n
Nothing -> "There is no C in the list."
This will return something like
"You can find C at position 2"
or
"There is no C in the list."
depending on whether or not there is a C in the list.
Making it convenient
Of course, this kind of pattern matching is unwieldy to write all the time, so there exists a function called maybe that does pretty much the same thing. If you look at its type signature, you see that
maybe :: b -> (a -> b) -> Maybe a -> b
So it takes a "default value" of type b, and a function from a to b, and will return a b. Whether or not this is the default value depends on whether or not the Maybe a value exists or is Nothing. For example, if you want to check if a list element is allowed entry into an 18+ club, you can do
maybe False (\n -> n >= 18) (elemIndex 'C' list)
This will say False if the index is less than 18 or if the element doesn't exist in the list. If it does exist, it will check if it's greater or equal to 18, and then return True.
Keeping the Just
What I've told you so far is how to get rid of the Just in a safe way. Sometimes, you can't get rid of the Just just yet – sometimes you have no sensible value to return if you have a Nothing on your hands instead of the Just. What you can do then is manipulate values when they are still inside the Just. For example, to subtract 15 from a value inside a just, you just do
fmap (subtract 15) (Just 23)
which will return
Just 8
So you see how fmap sort of takes a Just something value and applies the function to the something part of it, keeping the Just outside. If you would do
fmap (subtract 15) Nothing
it would just keep the Nothing, so the result would be
Nothing
Making it unsafe (kids, don't try this at home!)
Maybe is great because it is an error handling system that forces you to Do Things Right. You just can't ignore the possibility of an error (represented by Nothing.) Another common error handling system is terrible with this. That system is the system of exceptions. Nobody will know if you blatantly ignore that an exception can occur, which is a basis for very unsafe programs.
So you really want to keep the Just until you can toss it away and at the same time replace a potential Nothing value with something sensible.
If you can guarantee that there is no possibility of a Nothing value. If you know for sure that everytime you call elemIndex the element is going to be somewhere in the list, then it's okay to use fromJust. fromJust will blindly try to take a value out of a Just, without giving a dang about what happens if there is no Just there. fromJust will simply explode your program (throw an exception) if something went wrong.
As you understand, you have to use it with much care.
Being unsafe with style
However, as Jedai points out in a comment, even if you shouldn't be able to get a Nothing value, it is better to be explicit about it. Instead of using fromJust, consider doing something like
fromMaybe (error "The input " ++ show list ++ " shouldn't create a Nothing value!")
(elemIndex 'C' list)
which will blow up with a very specific error message, pinpointing where something must have gone wrong.
This is of course the same thing as the pattern match that looks like
case elemIndex 'C' list of
Just n -> n
Nothing -> error "The input " ++ show list ++ " shouldn't create a Nothing value!"
only compacted into the standard fromMaybe function.
Use fromJust from Data.Maybe. Like:
fromJust $ elemIndex 2 [1,2,3,4,5]
And you will get only 1.
But, this will fail if you don't have desired element in the list and you'll get an exception:
*** Exception: Maybe.fromJust: Nothing