Weird "Unbound Value" in Ocaml - module

I've encountered this problem where this code does not compile due to a Unbound Value error.
module Nim : Game =
struct
type state = int;;
type action = int;;
let getInitialState () = 21;;
let getActions e =
if e = 1 then [1] else
if e = 2 then [1;2] else
if e >= 3 then [1;2;3] else []
;;
let getResult e a = e-a;;
let isTerminal e = (e = 1 || e = 0);;
let getUtility e p = e;;
let getDepth () = 5;;
let print_action a = Printf.printf "On enlève %d allumettes. \n" a ;;
let print_state e = Printf.printf "Il y a %d allumettes. \n" e ;;
let partie (p:bool) =
let s = getInitialState () in
let rec partie_aux (j:bool) (st:state) =
if isTerminal st then (if st = 1 then not j else j) else
let () = print_state st in
let () = Printf.printf "Au tour du joueur %b. \n" j in
let rec check_move () =
let i = Stdlib.read_int () in
if List.mem i (getActions st) then i else ( let () = Printf.printf "Ce coup n'est pas valide ! Réessayer. \n" in check_move () )
in
let move = check_move () in
partie_aux (not j) (getResult st move)
in partie_aux p s
;;
(* Printf.printf "Le gagnant est le joueur %b ! \n" (partie true) ;; *)
end ;;
Printf.printf "Le gagnant est le joueur %b ! \n" (Nim.partie true) ;;
(*
module NimTest = MinimaxSearch (Nim) ;;
Nim.print_action (NimTest.makeDecision (Nim.getInitialState ()));;
Printf.printf "exploration de %d noeuds\n" (NimTest.getMetrics ());;
*)
The Nim module is, as far as I know, well implemented, but when I try to compile I get
File "tpjeux.ml", line 124, characters 50-60:
124 | Printf.printf "Le gagnant est le joueur %b ! \n" (Nim.partie true) ;;
^^^^^^^^^^
Error: Unbound value Nim.partie
I do not understand since the similar portion of code that is in comments works just fine when I uncomment it, does anyone know the reason for this ?

This has been answered in comments, but to sum it up, the issue is with the signature hiding a name.
A minimal example:
module type S =
sig
val foo : unit -> int
end
module A : S =
struct
let bar () = 42
let foo () = bar ()
end
We can call A.foo (), which internally calls bar () but if we try to directly call A.bar ()...
utop # A.bar () ;;
Error: Unbound value A.bar

Related

type error with CamlinternalFormatBasics.fmt

I am writing loop by recursion and I have problem:
let isRectangleIn a b c d =
if (a > c && b > d) || (a>d && b>c)
then
"TAK"
else
"NIE";;
let rec loop k =
if k = 0 then 0 else
let a = read_int () in
let b = read_int () in
let c = read_int () in
let d = read_int () in
Printf.printf "%s \n" (isRectangleIn a b c d)
loop (k-1);;
let i = read_int ();;
let result = loop i;;
Compiler says that
This expression has type
('a -> 'b -> 'c, out_channel, unit, unit, unit, 'a -> 'b -> 'c)
CamlinternalFormatBasics.fmt
but an expression was expected of type
('a -> 'b -> 'c, out_channel, unit, unit, unit, unit)
CamlinternalFormatBasics.fmt
Type 'a -> 'b -> 'c is not compatible with type unit
but I dont understand what i am doing wrong. Can somebody help me?
Whenever you see an error displaying CamlinternalFormatBasics.fmt, it means that a printf function is involved. Moreover, if there is a function type (here 'a -> 'b -> 'c) in the first parameter of the format, the error is that printf have too many argument compared to the format string.
In your case, the format string is "%s \n", which requires one argument, however you are using it with 3 arguments:
Printf.printf "%s \n" (isRectangleIn a b c d) loop (k-1)
(One can notice that there is as many supernumerary arguments in this function application and in the function type in the type error message.)
The root issue here is a missing ; between the printf expression and loop (k-1):
Printf.printf "%s \n" (isRectangleIn a b c d);
loop (k-1)
To avoid this kind of issue, it is generally advised to use ocp-indent (or ocamlformat) to indent code automatically and avoid deceitful indentation. For instance, ocp-indent would have indented your code as
Printf.printf "%s \n" (isRectangleIn a b c d)
loop (k-1);;
manisfesting the fact that printf and loop are not as the same level.

How to access a superclass method in octave?

I'm working with objects in octave and I would like to call the superclass set method in the subclass set. In the GNU octave documentation I haven't found how its works so I've tried to use the matlab documentation syntax but I get the next error: '' undefined near line 20 column 5 where the call is.
¿How could I access the superclass method correctly?
Here the code:
function s = set (o, varargin)
s = o;
if (length (varargin) < 2 || rem (length (varargin), 2) != 0)
error ([mfilename " :::: Expecting property/value pairs."]);
endif
while (length (varargin) > 1) #We get the first 2 pairs while exist.
prop = varargin{1};
val = varargin{2};
varargin(1:2) = [];
if (strcmp (prop, "color"))
if (ismember (val, ["black", "red", "green", "yellow", "blue", "violet", "cyan", "white"] )) #We check if val is a correct color.
s.color = val;
else
error ([mfilename " :::: Expecting the value for ""color"" to be a correct color."]);
endif
else
set#entity (s, prop,val);
endif
endwhile
endfunction
I'll add more details:
A simple example could be the next two classes:
try1, constructor and method (in his folder #try1):
function t = try1(x)
t.n = x;
t = class (t, "try1")
endfunction
function o = op(t,x)
o = t.n + x;
endfunction
try2 inherits from try1, constructor and method(in his folder #try2):
function t2 = try2(x)
t1 = #try1(x);
t.n = x;
t2 = class (t, "try2",t1);
endfunction
function o = op(t,x)
o = t.n - x;
endfunction
How to acces to op method of try1 with an instance of try2?
thanks :)
If you want to access the constructor of the parent class, just call it as you would normally outside the child class. Like so:
$ cat #try1/try1.m
function t = try1 (x)
t.n = x;
t = class (t, "try1");
endfunction
$ cat #try1/op.m
function o = op (t)
disp ("op() from try1");
o = t.n + 5;
endfunction
$ cat #try2/try2.m
function t2 = try2 (x)
t1 = #try1 (x);
t.n = x;
t2 = class (t, "try2", t1);
endfunction
$ cat #try2/op.m
function o = op (t)
o = op (t.t1);
endfunction
$ octave
octave:1> try2 (5)
ans = <class try2>
octave:2> op (ans)
op() from try1
ans = 10
See the manual section on Object Oriented Programming, specially the section on Inheritance and Aggregation

Picking which ocaml module to use with command line parameter

In my code I've module M = Implementation1 and then I reference M, instead of Implementation1. The problem is, I've to recompile my program to change Implementation1 to Implementation2. I'd like to control which implementation to use from with a command line parameter. Is that possible?
Is the situation simpler, when all implementations share signature?
Since both implementation are known statically you can use first class modules. There are quite a few different possibilities on how to structure your program, here's one that minimizes toplevel reference cells and toplevel effectful statements:
module type M = sig
val test : unit -> unit
end
module M1 : M = struct
let test () = Printf.printf "Implementation 1\n%!"
end
module M2 : M = struct
let test () = Printf.printf "Implementation 2\n%!"
end
let test m =
let module M = (val m : M) in
(* If other modules of your program depend on the implementation of
M, functorize them over sig M and instantiate them with M here. *)
M.test ()
let main () =
let exec = Filename.basename Sys.executable_name in
let usage = Printf.sprintf
"Usage: %s [OPTION]...\n\
Program synopsis.\n\
Options:" exec
in
let m = ref (module M1 : M) in
let options = [
"-m1", Arg.Unit (fun () -> m := (module M1 : M)),
" Use implementation 1 (default)";
"-m2", Arg.Unit (fun () -> m := (module M2 : M)),
" Use implementation 2"; ]
in
let anon _ = raise (Arg.Bad "no positional argument supported") in
Arg.parse (Arg.align options) anon usage;
test !m
let () = main ()
For most versions of OCaml you can do this with camlp4.
IFDEF USE_IMP1 THEN
module M = Implementation1
ELSE
module M = Implementation2
END
Then passing the pre-processing options like the following will choose the correct one to incorporate in the build.
-pp "camlp4of -UUSE_IMP1" //to undefine USE_IMP1
-pp "camlp4of -DUSE_IMP1" //to define USE_IMP2
For versions of OCaml >= 4.00.0 you can use the First-Class modules and an expression like,
module Choose = (val (if use_impl1 then (module Impl_1) else (module Impl_2)) : IMP)
to use an if statement to choose the module as determined by the use_impl1 value.

Extract common functions from 2 functors

I have defined a module type ZONE and two functors (ZoneFun and ZoneFunPrec) to build it:
(* zone.ml *)
module type ZONE =
sig
type info
type prop
type t = { p: prop; i: info }
val f1 : t -> string
end
module ZoneFun (Prop : PROP) = struct
type info = { a: int }
type prop = Prop.t
type t = { p: prop; i: info }
let f1 z = "f1"
end
(* zoneFunPrec.ml *)
module ZoneFunPrec (Prop: PROP) (Prec: ZONESM) = struct
type info = { a: int; b: Prec.t }
type prop = Prop.t
type t = { p: prop; i: info }
let f1 z = "f1"
let get_prec z = z.info.prec
end
Some functions in these 2 functors are implemented differently (e.g. f0); some functions are exactly the same (e.g. f1). My question is how to extract those common functions to avoid from implementing them twice?
Edit: (I realize that I need to give more specific information to make it clearer... Sorry about the change...)
There are some differences between ZoneFun and ZoneFunPrec:
1) their type info are not same
2) ZoneFunPrec has get_prec that ZoneFun doesn't have, and the signture of ZONE doesn't require it.
So later I can write module ZoneB = ZoneFun(B) and module ZoneA = ZoneFunPrec(C)(ZonesmD) to build the zones...
You can do the following:
module ZoneFunPrec (Prop: PROP) = struct
module Zone1 = ZoneFun(Prop)
type prop = Prop.t
type t = string
let f0 x = "f0 in ZoneFunPrec"
let f1 = Zone1.f1
end
But this will only work if you do not ascribe the signature in the functor
module ZoneFunPrec (Prop: PROP) : ZONE = ...
If you want opaque ascription, you could do something like this
(* No ascription here *)
module SharedFn (Prop : PROP) = struct
type prop = Prop.t
type t = string
let f0 x = "f0 in ZoneFun"
let f1 x = "f1"
end
(* Ascribe the module to hide the types *)
module ZoneFun (Prop : PROP) : ZONE = struct
module Shared = SharedFn(Prop)
let f1 = Shared.f1
...defs specific to ZONE...
end
module ZoneFunPrec (Prop: PROP) : ZONE_PREC = struct
module Shared = SharedFn(Prop)
type prop = Prop.t
type t = string
let f0 x = "f0 in ZoneFunPrec"
let f1 = Shared.f1
...defs specific to ZONE_PREC...
end
You can try using include Shared to save typing, but the types will be abstract so it won't be very flexible.

Define a static variable for a recursive function in OCaml

I have a recursive function fact, which can be called from either an expression inside it or an expression outside it.
I would like to associate fact with a variable v, such that each time fact is called from outside (another function), v is initialized, and its value can be changed inside fact, but never can be initialized when fact is called from inside.
The following code suits my need, but one problem is that v is defined as a global variable, and I have to do v := init before calling fact from outside, which I do not find beautiful.
let init = 100
let v = ref init
let rec fact (n: int) : int =
v := !v + 1;
if n <= 0 then 1 else n * fact (n - 1)
let rec fib (n: int) : int =
if n <= 0 then 0
else if n = 1 then (v := !v + 50; 1)
else fib (n-1) + fib (n-2)
let main =
v := init;
print_int (fact 3);
print_int !v; (* 104 is expected *)
v := init;
print_int (fib 3);
print_int !v;; (* 200 is expected *)
Could anyone think of a better implementation?
You can hide the function and value definitions within the body of a containing function as follows:
open Printf
let init = 100
let fact n =
let rec fact counter n =
incr counter;
if n <= 0 then 1 else n * fact counter (n - 1)
in
let counter = ref init in
let result = fact counter n in
(result, !counter)
let main () =
let x, count = fact 3 in
printf "%i\n" x;
printf "counter: %i\n" count (* 104 is expected *)
let () = main ()
You can adapt Martin's solution so that data is shared across various calls:
let fact =
let counter = ref 0 in
fun n ->
let rec fact = ... in
fact n
The idea is to transform let fact = fun n -> let counter = ... in ... into let fact = let counter = ... in fun n -> ...: counter is initialized once, instead of at each call of fact.
A classical example of this style is:
let counter =
let count = ref (-1) in
fun () ->
incr count;
!count
Beware however that you may get into typing trouble if the function was meant to be polymorphic: let foo = fun n -> ... is always generalized into a polymorphic function, let foo = (let x = ref ... in fun n -> ...) is not, as that would be unsound, so foo won't have a polymorphic type.
You can even generalize the counter example above to a counter factory:
let make_counter () =
let count = ref (-1) in
fun () ->
incr count;
!count
For each call to make_counter (), you get a new counter, that is a function that shares state across call, but whose state is independent from previous make_counter () counter creations.
With Ocaml's objects, you can do:
class type fact_counter = object ('self)
method get : int
method set : int -> unit
method inc : unit
method fact : int -> int
end;;
class myCounter init : fact_counter = object (self)
val mutable count = init
method get = count
method set n = count <- n
method inc = count <- count + 1
method fact n =
self#inc;
if n <= 0 then 1 else n * self#fact (n - 1)
end;;
Then you can obtain:
# let c = new myCounter 0;;
val c : myCounter = <obj>
# c#fact 10;;
- : int = 3628800
# c#get;;
- : int = 11
# c#set 42;;
- : unit = ()
# c#fact 10;;
- : int = 3628800
# c#get;;
- : int = 53
I hope you can easily see how to adapt myCounter to include fib ...