Why this code works in interactive but fails when compiled? - ocaml

I'm a complete newbie in OCaml and trying to create a simple console program.
(*let k = read_int()
let l = read_int()
let m = read_int()
let n = read_int()
let d = read_int()*)
let k = 5
let l = 2
let m = 3
let n = 4
let d = 42
let rec total: int -> int -> int = fun i acc ->
if i > d then
acc
else
if (i mod k) == 0 || (i mod l) == 0 || (i mod m) == 0 || (i mod n) == 0 then
total (i + 1) (acc + 1)
else
total (i + 1) acc;
print_int (total 1 0)
But if I try to compile it, it fails:
PS C:\Users\user> ocamlc -g .\a148.ml
File ".\a148.ml", line 14, characters 2-180:
Warning S: this expression should have type unit.
File ".\a148.ml", line 22, characters 0-21:
Error: This expression has type unit but is here used with type int
So, looks like if expression cannot return value here (why?). I've added let binding
let k = 5
let l = 2
let m = 3
let n = 4
let d = 42
let rec total: int -> int -> int = fun i acc ->
let x' = if i > d then
acc
else
if (i mod k) == 0 || (i mod l) == 0 || (i mod m) == 0 || (i mod n) == 0 then
total (i + 1) (acc + 1)
else
total (i + 1) acc;
x'
print_int (total 1 0)
and it works, but raises another error:
File ".\a148.ml", line 23, characters 0-0:
Error: Syntax error
Line 23 is the next to print_int statement and empty, so it seems like compiler wants something else from me, but I don't know what.
UPD: ok, the working code:
let k = 5 in
let l = 2 in
let m = 3 in
let n = 4 in
let d = 42 in
let rec total i acc =
if i > d then
acc
else
if (i mod k) == 0 || (i mod l) == 0 || (i mod m) == 0 || (i mod n) == 0 then
total (i + 1) (acc + 1)
else
total (i + 1) acc
in let x = total 1 0 in
print_int x;

The problem is the misuse of semicolon (;).
Semicolon intends to be the sequence composition of two expressions. S1 ; S2 means that the compiler expects S1 to be unit type, computes S1 and S2 in that order and returns the result of S2.
Here you mistakenly use ;, so OCaml expects the second if...then...else to return unit and wants you to provide one more expression. Removing ; and adding necessary in(s) should make the function compile:
let k = 5 in
let l = 2 in
let m = 3 in
let n = 4 in
let d = 42 in
let rec total: int -> int -> int = fun i acc ->
if i > d then
acc
else
if (i mod k) == 0 || (i mod l) == 0 || (i mod m) == 0 || (i mod n) == 0 then
total (i + 1) (acc + 1)
else
total (i + 1) acc
Regarding your second function, you should replace ; by in to indicate that x' is used to compute the return value.
BTW, your total function looks weird since you use lambda expression in the function body. Explicit declaration is more readable:
let rec total i acc =
if i > d then
acc
else if i mod k = 0 || i mod l = 0 || i mod m = 0 || i mod n = 0 then
total (i + 1) (acc + 1)
else
total (i + 1) acc
I have also changed reference equality (==) to structural equality (=) though there is no difference among them in integer.

Related

Syntax Error when calling Recursive Function inside a Recursive Function in Ocaml

The compiler returns a Syntax error when using the command in
xyz aux
if((match4242 aux) = 0) then main (!list) else 1
Here's my full code.
open Printf
open Format
let regraUm m = m/2
let regraDois m = ((m / 10) mod 10) * (m mod 10)
let regraTres m = 42
let match4242 list =
let a = ref 0 in
let rec match42 list =
match list with
|[]->[]
|m::body->
begin
if (m = 42) then a := 1;
match42 body
end
in match42 list;
!a
let rec main aux =
let list = ref [] in
let rec xyz aux =
let () = List.iter (fun x -> printf "%d " x) aux in
match aux with
|[]->[]
|m::body ->
begin
if ((m mod 2) = 0) then list := (m - (regraUm m))::!list;
if ((m mod 3) = 0) || ((m mod 4) = 0) then
if (regraDois m <> 0) then
list := (m - (regraDois m)) ::!list;
if ((m mod 5) = 0) then list := (m - (regraTres m))::!list;
xyz body
end
in xyz aux
if((match4242 aux) = 0) then main (!list) else 1
The program checks if 42 is inside the list, if not then it calls itself again following a set of rules of division, subtraction, etc.
I don't know if this last info is helpful to debug this piece of code.
These two lines:
xyz aux
if ((match4242 aux) = 0) then main (!list) else 1
Represent a single expression, since they aren't separated by ;. But indeed you can't have an if expression in this position (function argument) unless you parenthesize it.
Most likely you want ; after aux here.

Syntax error when Calling function inside function in Ocaml

I am getting a Syntax error when calling the function f and g inside lp and assigning them to y and z
let lp m =
let y = f m in
let z = g y (List.length y) m;
Here's my full code:
open Printf
open Format
let regraUm m = m/2
let regraDois m = ((m / 10) mod 10) * (m mod 10)
let regraTres m = 42
let f m =
let list = ref [] in
if ((m mod 2) = 0) then list := 1::!list;
if ((m mod 3) = 0) || ((m mod 4) = 0) then list := 2::!list;
if ((m mod 5) = 0) then list := 3::!list;
!list
let g list len m =
let res = ref [] in
for i = 0 to (len-1) do
let regra = List.nth list i in
if (regra = 1) then res := (m - (regraUm m))::!res;
if (regra = 2) || ((m mod 4) = 0) then res := (m - (regraDois m))::!res;
if (regra = 3) then res := (m - (regraTres m))::!res;
done;
!res
let lp m =
let y = f m in
let z = g y (List.length y) m;
Syntax Error:
ocamlopt regras.ml -o r
File "regras.ml", line 33, characters 4-4:
Error: Syntax error
f and g work properly when used outside of a function.
A let binding need some expression to be attached after an in, which in your case doesn't exist. In this case your code would work either adding z as expression or removing the binding leaving just the expression.
let lp m =
let y = f m in
let z = g y (List.length y) m in
z
Or this
let lp m =
let y = f m in
g y (List.length y) m

Write the function residue l n which calculates the residue of n by l by making an iterative calculation

I want to write the function residue l n which calculates the residue of n by l by making an iterative calculation starting with n and using the items in the list in order. The calculation is as follows:
-initially the residue is the value of n
-each element e of l (taken in the order of the list) changes the residue in the following way:
if e and the residue are of the same parity (both even or both odd) then the new residue is the sum of r and e, otherwise it is the difference between r and e (r-e).
-the last residue is the result of the game.
Example: residu [1;3] 7 returns 5 as a result of the following calculations:
7 + 1 (same parity +) = 8
8 - 3 (parité différente -) = 5
This is my code but it doesn't seem to be working:
let rec residue l n =
if l = [] then 0 else
if (((List.hd l) mod 2 <> 0) && (n mod 2 <> 0 )) || (((List.hd l) mod 2 == 0) && (n mod 2 == 0 ))
then
(List.hd l) + residue (List.tl l) ((List.hd l)+ n) else
n - (List.hd l) - residue (List.tl l) (n - (List.hd l));;
residu [1;3] 7;;
- : int = 6 (The correct result should be 5)
Thank you for your help.
Here is my stab at it.
let rec residue l n =
let parity a b =
if ((a mod 2 <> 0) && (b mod 2 <> 0)) ||
((a mod 2 == 0) && (b mod 2 == 0)) then true else false in
match l, n with
| [], n -> n
| (x::xs), n -> if parity x n then residue xs (n+x) else residue xs (n-x)
Hope it helps for figuring out the problem.

Ocaml :This expression has type bool but an expression was expected of type unit

I got some issue with my code I don't understand. Why did I get this error: This expression has type bool but an expression was expected of type unit. Here is the code
let well_formed (_dimension : int) (_initial1 : _ list)
(_initial2 : _ list) : bool =
if List.length _initial1 + List.length _initial2 != 4 * _dimension then false
else if List.length _initial1 != List.length _initial2 then false
else
let c = 0 in
for i = 1 to _dimension do
let liste =
List.filter (fun x -> x == i) _initial1
# List.filter (fun x -> x == i) _initial2
in
if List.length liste == 4 then c = c + 1 else c = c
done;
if c == _dimension then true else false
I reformated your code, actually for loop have no impact on your code.
let well_formed dimension initial1 initial2 =
let ll1 = List.length initial1 in
let ll2 = List.length initial2 in
let total_list_length = ll1 + ll2 in
if total_list_length != (4 * dimension) then false else
if ll1 != ll2 then false else
let c = 0 in
(* this code do nothing : what is expected ?
for i = 1 to dimension do
let liste = (List.filter(fun x -> x == i) initial1 )#(List.filter(fun x->x == i) initial2) in
if ( List.length liste ) == 4 then c = c+1 else c = c
done;
*)
if c == dimension then true else false
You need to learn imperative features of ocaml if you want to write code this way.
For example c = c + 1 return false
if you want to increment a variable you need to create a ref variable.
OCaml is not C/Python/Javascript, in particular
x = x + 1
means the same as
x == x + 1
in C or Python, i.e., it is a comparison operator. The == operator is the physical comparison (the same as === in Javascript).
Also, integers in OCaml are immutable, so if you want to have a mutable number you need to wrap it in a reference and use := for assignment, e.g.,
let x = ref 0 in
for i = 0 to 5 do
x := !x + 2
done

F# Performance: What is making this code so slow?

This F# code is an attempt to solve Project Euler problem #58:
let inc = function
| n -> n + 1
let is_prime = function
| 2 -> true
| n when n < 2 || n%2=0-> false
| n ->
[3..2..(int (sqrt (float n)))]
|> List.tryFind (fun i -> n%i=0)
|> Option.isNone
let spir = Seq.initInfinite (fun i ->
let n = i%4
let a = 2 * (i/4 + 1)
(a*n) + a + (a-1)*(a-1))
let rec accum se p n =
match se with
| x when p*10 < n && p <> 0 -> 2*(n/4) + 1
| x when is_prime (Seq.head x) -> accum (Seq.tail x) (inc p) (inc n)
| x -> accum (Seq.tail x) p (inc n)
| _ -> 0
printfn "%d" (accum spir 0 1)
I do not know the running time of this program because I refused to wait for it to finish. Instead, I wrote this code imperatively in C++:
#include "stdafx.h"
#include "math.h"
#include <iostream>
using namespace std;
int is_prime(int n)
{
if (n % 2 == 0) return 0;
for (int i = 3; i <= sqrt(n); i+=2)
{
if (n%i == 0)
{
return 0;
}
}
return 1;
}
int spir(int i)
{
int n = i % 4;
int a = 2 * (i / 4 + 1);
return (a*n) + a + ((a - 1)*(a - 1));
}
int main()
{
int n = 1, p = 0, i = 0;
cout << "start" << endl;
while (p*10 >= n || p == 0)
{
p += is_prime(spir(i));
n++; i++;
}
cout << 2*(i/4) + 1;
return 0;
}
The above code runs in less than 2 seconds and gets the correct answer.
What is making the F# code run so slowly? Even after using some of the profiling tools mentioned in an old Stackoverflow post, I still cannot figure out what expensive operations are happening.
Edit #1
With rmunn's post, I was able to come up with a different implementation that gets the answer in a little under 30 seconds:
let inc = function
| n -> n + 1
let is_prime = function
| 2 -> true
| n when n < 2 || n%2=0-> false
| n ->
[3..2..(int (sqrt (float n)))]
|> List.tryFind (fun i -> n%i=0)
|> Option.isNone
let spir2 =
List.unfold (fun state ->
let p = fst state
let i = snd state
let n = i%4
let a = 2 * (i/4 + 1)
let diag = (a*n) + a + (a-1)*(a-1)
if p*10 < (i+1) && p <> 0 then
printfn "%d" (2*((i+1)/4) + 1)
None
elif is_prime diag then
Some(diag, (inc p, inc i))
else Some(diag, (p, inc i))) (0, 0)
Edit #2
With FuleSnabel's informative post, his is_prime function makes the above code run in under a tenth of a second, making it faster than the C++ code:
let inc = function
| n -> n + 1
let is_prime = function
| 1 -> false
| 2 -> true
| v when v % 2 = 0 -> false
| v ->
let stop = v |> float |> sqrt |> int
let rec loop vv =
if vv <= stop then
if (v % vv) <> 0 then
loop (vv + 2)
else
false
else
true
loop 3
let spir2 =
List.unfold (fun state ->
let p = fst state
let i = snd state
let n = i%4
let a = 2 * (i/4 + 1)
let diag = (a*n) + a + (a-1)*(a-1)
if p*10 < (i+1) && p <> 0 then
printfn "%d" (2*((i+1)/4) + 1)
None
elif i <> 3 && is_prime diag then
Some(diag, (inc p, inc i))
else Some(diag, (p, inc i))) (0, 0)
There is no Seq.tail function in the core F# library (UPDATE: Yes there is, see comments), so I assume you're using the Seq.tail function from FSharpx.Collections. If you're using a different implementation of Seq.tail, it's probably similar -- and it's almost certainly the cause of your problems, because it's not O(1) like you think it is. Getting the tail of a List is O(1) because of how List is implemented (as a series of cons cells). But getting the tail of a Seq ends up creating a brand new Seq from the original enumerable, discarding one item from it, and returning the rest of its items. When you go through your accum loop a second time, you call Seq.tail on that "skip 1 then return" seq. So now you have a Seq which I'll call S2, which asks S1 for an IEnumerable, skips the first item of S1, and returns the rest of it. S1, when asked for its first item, asks S0 (the original Seq) for an enumerable, skips its first item, then returns the rest of it. So for S2 to skip two items, it had to create two seqs. Now on your next run through when you ask for the Seq.tail of S2, you create S3 that asks S2 for an IEnumerable, which asks S1 for an IEnumerable, which asks S0 for an IEnumerable... and so on. This is effectively O(N^2), when you thought you were writing an O(N) operation.
I'm afraid I don't have time right now to figure out a solution for you; using List.tail won't help since you need an infinite sequence. But perhaps just knowing about the Seq.tail gotcha is enough to get you started, so I'll post this answer now even though it's not complete.
If you need more help, comment on this answer and I'll come back to it when I have time -- but that might not be for several days, so hopefully others will also answer your question.
Writing performant F# is very possible but requires some knowledge of patterns that have high relative CPU cost in a tight loop. I recommend using tools like ILSpy to find hidden overhead.
For instance one could imagine F# exands this expression into an effective for loop:
[3..2..(int (sqrt (float n)))]
|> List.tryFind (fun i -> n%i=0)
|> Option.isNone
However it currently doesn't. Instead it creates a List that spans the range using intrinsic operators and passes that to List.tryFind. This is expensive when compared to the actual work we like to do (the modulus operation). ILSpy decompiles the code above into something like this:
public static bool is_prime(int _arg1)
{
switch (_arg1)
{
case 2:
return true;
default:
return _arg1 >= 2 && _arg1 % 2 != 0 && ListModule.TryFind<int>(new Program.Original.is_prime#10(_arg1), SeqModule.ToList<int>(Operators.CreateSequence<int>(Operators.OperatorIntrinsics.RangeInt32(3, 2, (int)Math.Sqrt((double)_arg1))))) == null;
}
}
These operators aren't as performant as they could be (AFAIK this is currently being improved) but no matter how effecient allocating a List and then search it won't beat a for loop.
This means the is_prime is not as effective as it could be. Instead one could do something like this:
let is_prime = function
| 1 -> false
| 2 -> true
| v when v % 2 = 0 -> false
| v ->
let stop = v |> float |> sqrt |> int
let rec loop vv =
if vv <= stop then
(v % vv) <> 0 && loop (vv + 2)
else
true
loop 3
This version of is_prime relies on tail call optimization in F# to expand the loop into an efficient for loop (you can see this using ILSpy). ILSpy decompile the loop into something like this:
while (vv <= stop)
{
if (_arg1 % vv == 0)
{
return false;
}
int arg_13_0 = _arg1;
int arg_11_0 = stop;
vv += 2;
stop = arg_11_0;
_arg1 = arg_13_0;
}
This loop doesn't allocate memory and is just a rather efficient loop. One see some non-sensical assignments but hopefully the JIT:er eliminate those. I am sure is_prime can be improved even further.
When using Seq in performant code one have to keep in mind it's lazy and it doesn't use memoization by default (see Seq.cache). Therefore one might easily end up doing the same work over and over again (see #rmunn answer).
In addition Seq isn't especially effective because of how IEnumerable/IEnumerator are designed. Better options are for instance Nessos Streams (available on nuget).
In case you are interested I did a quick implementation that relies on a simple Push Stream which seems decently performant:
// Receiver<'T> is a callback that receives a value.
// Returns true if it wants more values, false otherwise.
type Receiver<'T> = 'T -> bool
// Stream<'T> is function that accepts a Receiver<'T>
// This means Stream<'T> is a push stream (as opposed to Seq that uses pull)
type Stream<'T> = Receiver<'T> -> unit
// is_prime returns true if the input is prime, false otherwise
let is_prime = function
| 1 -> false
| 2 -> true
| v when v % 2 = 0 -> false
| v ->
let stop = v |> float |> sqrt |> int
let rec loop vv =
if vv <= stop then
(v % vv) <> 0 && loop (vv + 2)
else
true
loop 3
// tryFind looks for the first value in the input stream for f v = true.
// If found tryFind returns Some v, None otherwise
let tryFind f (s : Stream<'T>) : 'T option =
let res = ref None
s (fun v -> if f v then res := Some v; false else true)
!res
// diagonals generates a tuple stream of all diagonal values
// The first value is the side length, the second value is the diagonal value
let diagonals : Stream<int*int> =
fun r ->
let rec loop side v =
let step = side - 1
if r (side, v + 1*step) && r (side, v + 2*step) && r (side, v + 3*step) && r (side, v + 4*step) then
loop (side + 2) (v + 4*step)
if r (1, 1) then loop 3 1
// ratio computes the streaming ratio for f v = true
let ratio f (s : Stream<'T>) : Stream<float*'T> =
fun r ->
let inc r = r := !r + 1.
let acc = ref 0.
let count = ref 0.
s (fun v -> (inc count; if f v then inc acc); r (!acc/(!count), v))
let result =
diagonals
|> ratio (snd >> is_prime)
|> tryFind (fun (r, (_, v)) -> v > 1 && r < 0.1)