I'm having an array in ocaml.array of type float option array array
for example :- [|[|Some 2.3;None;None|];[|Some 1.2;Some 2.4;None|]|]
I have to add elements of that array. If I encounter None then we have to raise error else I have to add elements and return it.
So I'm using for loop I'm not understanding how to raise exception in middle of loop and exit loop
Entire code should be in Ocaml
Well, we're not going to write your code for you :-). But the expression:
raise exn
will work anywhere (including in a for loop) to raise the given exception.
Here's an example using List.iter that looks for the first odd number:
let find_odd list =
let exception Found_it of int in
let look k = if k mod 2 = 1 then raise (Found_it k) in
try List.iter look list; None
with Found_it n -> Some n
Related
I wrote this ocaml function:
(* int Base.List.t -> Base.Int.t x Base.Int.t *)
let min_and_max lst =
let mmax = ref Float.neg_infinity
and mmin = ref Float.infinity in
List.iter ~f:(fun v -> let fv = Float.of_int v in
if fv > !mmax then mmax := fv
else if fv < mmin then mmin := fv)
lst;
(Int.of_float !mmin, Int.of_float !mmax)
It is supposed to return the min and max of a list of integers, but when I compile, I get this error:
File "02-exercises/24-refs/problem.ml", line 25, characters 21-23:
Error: This expression has type Base.Float.t = float
but an expression was expected of type int
The error is pointing to the first if statement in that function. I must be making a very obvious mistake, but I can't see it.
Solution taking into account the answers and comments so far:
let min_and_max lst =
match lst with
| [] -> failwith "Cannot find min and max of empty list"
| v::[] -> (v,v)
| a::b::rest ->
let mmax = ref (max a b)
and mmin = ref (min a b) in
List.iter ~f:(fun v ->
if v > !mmax then mmax := v;
if v < !mmin then mmin := v)
rest;
(!mmin, !mmax)
Base disables polymorphic comparison: you need to use a local open to compare floats with > or < : Float.(fv > !mmax ).
p.s.: The gratuitous conversion to float (and the use of references) is a bit strange and non-optimal.
I don't understand how your compiler throws you that error. Your code contains several errors that it should detect before:
You make a wrong use of the label.
In the else arm, you are comparing against the ref mmin and not against its content —you missed the !—.
You confuse int_of_float function with Int.of_float, that don't exists.
In addition, the logical principle of the function isn't adequate. For example, the first value of the list will always enter in the mmax variable, because it will be greater than the negative infinity. But what if this value were the minimum?
Apart from the above, converting an integer to a float in this case is meaningless and causes precision loss and performance decrease. Nor is necessary to use refs.
This isn't a canonical way to proceed in a OCaml context. In OCaml it's important to try to find the simplest possible solution, because as soon as you start to complicate with the types, you end up being unable to solve the disaster.
I propose you a simpler solution for the problem, with the license to compose a polymorphic function, not only to integers:
let min_and_max lst =
(List.fold_left (fun a b -> if a < b then a else b) (List.hd lst) lst),
(List.fold_left (fun a b -> if a > b then a else b) (List.hd lst) lst);;
It's an elegant option and in addition it's based on terminal recursion. However, on that scheme you could redefine the functions yourself without using the predefined ones to go through the lists. You could also choose the two numbers with a single round, but it would be somewhat more complex to do.
fun first_answer(my_f:('a -> 'b option)) : 'a list -> 'b =
let
fun help(_a:'a list) : 'a =
(((List.map valOf)o(List.filter isSome)o(List.map my_f)) _a)
in
help
end;
Error: syntax error: replacing WILD with SEMICOLON
Something with that _a is messing it up..... The error is linked to the last usage of _a
I am not getting very far, and I've rearranged the logic many ways already. As you can see the first_answer returns takes a function and returns a function. This is what I am doing here and I am following the types as far as I know. There is probably something simple that I am not seeing.
It's simple indeed: an identifier cannot start with an underscore. So _a is parsed as if you had written _ a, in accordance with the usual maximal munch rule for lexical syntax.
Edit: Extra tip: Your function does not have the type 'a list -> 'b, because help returns a list of 'bs, not a single value of type 'b. Moreover, as written, it can be implemented more easily as
fun first_answer f xs = List.mapPartial f xs
or, in fact,
val first_answer = List.mapPartial
I want to use a stack inside a Haskell function but I don't know how to use it. My function is supposed to work like this :
Take a string
Put some elements of this input string to output string and put others to stack.
Pop elements to that output string too.
Do 2 and 3 recursively until stack is empty.
Print the output string when stack is empty.
I don't know when and where to create that stack. I couldn't figure it out myself since I'm very new at Haskell programming. Since I haven't created any code I can't show any code either. Can you tell me what the function will look like in an algorithmic way? Where should I define the stack and output string? Thanks.
One comfortable thing here is that standard Haskell list is a fine stack (natural, bearing in mind that stack is a more restricted kind of list). Your function might look something like this:
--takes one string and uses a stack to convert it to another string
doSomethingWithStack :: String -> [String] -> String
doSomethingWithStack str stack =
let str' = --here you embody your points 2 and 3
stack' = --stack top is (head stack), push is (x : stack), pop is (tail stack)
--... any change you'd want to make to any value turns into a new variable
in case stack'' of --check the final variables
[] -> str'' --if stack is empty, end
_ -> doSomethingWithStack str'' stack'' --if not, repeat
--now, to make it pretty
fancyWrapper :: String -> String
fancyWrapper str = doSomethingWithStack str [] -- empty list is an empty stack
--because you should strive to separate pure and impure functions
--, I suggest that you do the print elsewhere, say
main = do
str <- getLine
print $ fancyWrapper str
Hopefully that is neither too little nor too much. Give it a try and ask more specific questions, once you run into problems.
Given the following code :
exception E of int;
fun g(y) = raise E(y);
fun f(x) =
let
exception E of real;
fun z(y)= raise E(y);
in
x(3.0);
z(3)
end;
f(g);
When executing the code in SML I get :
stdIn:216.8-216.12 Error: operator and operand don't agree [literal]
operator domain: real
operand: int
in expression:
z 3
That's fine - I understand that the line z(3); causes an error , since z throws int instead of real .
But my problem is with the line x(3.0); , why doesn't it cause an error ?
From my understanding , x is g(y) , then when we execute x(3.0) we actually execute g(3.0) , but g throws only exceptions of type int , but we passed to g the value 3.0 ,hence g would throw a real value , so it's supposed to be a violation , doesn't it ?
I'd appreciate if someone can explain why no error is happening when executing x(3.0) .
Thanks
EDIT:
When I remove z(3); , meaning :
- fun f(x) =
= let
= exception E of real;
= fun z(y)= raise E(y);
= in
= x(3.0)
=
= end;
val f = fn : (real -> 'a) -> 'a
- f(g);
The output is :
stdIn:11.1-11.5 Error: operator and operand don't agree [tycon mismatch]
operator domain: real -> 'Z
operand: int -> 'Y
in expression:
f g
-
So , as U can see , in both cases we'll get error .
Hence , I'm back at square one : why when both x(3.0) and z(3) appear (see code 1 , the first code posted at the beginning of the post) one after the other , why does SML only refers to the error that the second line (z(3);) caused , and not to the error that
the first line caused (x(3.0);) .
10x again
To complement Jesper's excellent answer: In other words, there is nothing wrong with the call to x inside f. If you remove the erroneous call to z, and then type f into an SML prompt, then you should see that the type system has inferred the type
(real -> 'a) -> 'a
for it. That type is perfectly fine, it is merely the call to f later on in your program that is ill-typed. because g does not match the parameter type real -> 'a as required.
Your problem lies in the fact that x is a function that is passed along to f, thus when typing the function f, it will always give the correct type to the argument x, as it is not bound by anything. The fact that you are have a function application f(g) right after plays no role when inferring the types of the function f.
If we move the local function z outside the definition of f, we end up with something a lot simpler, which will type
exception R of real;
fun z(y)= raise R (y);
exception I of int;
fun g(y) = raise I (y);
fun f(i, r) = (i(3.0); r(3))
However when we then call f(g,z) we end up with the following error, as the two functions aren't of the correct type
- f(g, z);
stdIn:78.1-78.8 Error: operator and operand don't agree [tycon mismatch]
operator domain: (real -> 'Z) * (int -> 'Y)
operand: (int -> 'X) * (real -> 'W)
in expression:
f (g,z)
The initial misunderstanding stemmed from not understanding when the type error was detected. Standard ML is a strongly STATICALLY typed language. This means that the type checking is all done at compile time, when the function is first read by the interpreter, not at run-time. This means that the type error is generated before the code is ever executed, which Jesper correctly pointed out. The two type errors are exactly where Jesper indicated, in the f(g) expression and the z(3) expression. There is nothing wrong with the expression x(3.0) when the expression is compiled. There would only be a problem there if static type checking did not prevent the program from running at all. A dynamically typed language like Python would allow this program to run and raise an exception where Ron suggests when the x(3.0) expression was evaluated.
I am not sure if this is a stupid question but I was going through the tutorial that comes with VS 2010 and there is a function like this:
let rec factorial n = if n=0 then 1 else n * factorial (n-1)
What's the reason of this recursive function to be marked with the rec keyword?
Is it so that the compiler is assured of it being recursive so can do certain optimizations?
What happens if you exclude it?
This might be instructive:
let Main() =
let f(x) =
printfn "original f: %d" x
let f(x) =
//let rec f(x) =
printfn "entered new f: %d" x
if x > 0 then
f(x-1)
else
printfn "done"
f(3)
Main()
That prints
entered new f: 3
original f: 2
Now if we comment out let and uncomment let rec, then it prints
entered new f: 3
entered new f: 2
entered new f: 1
entered new f: 0
done
So from that point of view, it's just about name binding; let rec puts the identifier in scope immediately (in this example, shadowing the previous f), whereas let puts the identifier in scope only after its body is defined.
The motivation for the rule does stem from interactions with type inference.
According to Chris Smith (works on the F# team) -
It's to inform the type inference system to allow the function to be used as part of the type inference process. rec allows you to call the function before the type inference system has determined the function's type
According to the MSDN, it's only a syntatic necessity:
Recursive functions, functions that
call themselves, are identified
explicitly in the F# language. This
makes the identifer that is being
defined available in the scope of the
function.
http://msdn.microsoft.com/en-us/library/dd233232.aspx
What's the reason of this recursive function to be marked with the rec keyword?
To tell the compiler that any uses of the function name inside the body of the function refer to it recursively rather than to a previously-defined value of the same name.
Is it so that the compiler is assured of it being recursive so can do certain optimizations?
No.
What happens if you exclude it?
You lose the ability for the function you are defining to refer to itself in its function body and gain the ability to refer to previously-defined values of the same name.
It's necessary so that the function can be recursive. A non-rec function only knows about bindings at the place where it's defined, not after (so it doesn't know about itself).