I'm using OCamldebug to debug OCaml program of version 4.01.0. Just as debug info followed, the debugger breaks at line 61(where indicated as "<|b|>"). When i was trying to view data inside class "re". The debugger just print the type info instead of giving any tips for the class.
(ocd) list
51 re#adjust_jmpref il'
52 (* |> re#add_func_label u_fl *)
53 |> cfg#visit
54 in
55
56 let fbl = cfg#get_fbl in
57 let bbl = cfg#get_bbl in
58 let cfg_t = cfg#get_cfg_table il' in
59 let cg = cg#get_cg_table in
60 let il = re#add_bblock_label bbl il' in
61 (<|b|>fbl, bbl, cfg_t, cg, il, re)
62
63
64 let post_analyze il re =
65 ( re#unify_loc il
66 |> pp_print_list
67 |> re#adjust_globallabel ## global_bss ()
68 |> pp_print_file);
69
70 end
Position out of range.
(ocd) print self
Unbound identifier self
(ocd) print re
re:
< add_bblock_label : Type.bblock list -> Type.instr list -> 'a;
adjust_jmpref : 'b -> Type.instr list; adjust_loclabel : 'c -> 'b;
reassemble_dump : Type.func list -> 'd; share_lib_processing : 'e -> 'c;
visit_type_infer_analysis : 'f list -> Type.instr list -> 'e; .. >
= <obj>
(ocd) print re#instr
Unbound identifier
Part of definition of Class re is as followed.(about 2300 lines of codes).
class reassemble =
let data_set = Hashtbl.create 200
and plt_hash = Hashtbl.create 50
and pic_hash = Hashtbl.create 3
and text_set = Hashtbl.create 30 in
object(self)
inherit ailVisitor
val mutable label : (string*int) list = []
(* collect relocation info in c2d *)
val mutable c2d_addr: int list = []
val mutable deslist: string list = []
(* only collect the relocated symbol *)
val mutable deslist_reloc: int list = []
val mutable init_array_list: string list = []
val mutable eh_frame_list: string list = []
val mutable excpt_tbl_list: string list = []
val mutable jmpreflist: string list = []
val mutable sec : section list = []
val mutable instr_list: instr list = []
val mutable text_sec: (int*int) = (0,0) (* begin addr, size*)
val mutable plt_sec: (int*int) = (0,0) (* begin addr, size*)
val mutable text_mem_addrs: string list = []
And i've tried a demo file for OCamldebug and error still occurred.
I'm sure that i'm trying to print the correct identifiers of the class members. I didn't find any help in OCamldebug help info. What should i do if i'd like to view data inside classes?
Let's set up a demo and see how its behaving...
class a_demo_class =
object (self)
val inaccessible_val: string = "Hello"
method accessible_method: string = "Hello"
end ;;
let demo = new a_demo_class;;
demo#accessible_method;;
demo#inaccessible_val;; (* This errors*)
The second access throws...
Error: This expression has type a_demo_class
It has no method inaccessible_val
Related
can you help me out, i made this program to get an output from some .txt file like this :
john:3:uk
paul:18:us
#load "str.cma"
let f_test = "/home/test.txt" ;;
(*
Recursive Reading function
*)
let read_lines f_test : string list =
if Sys.file_exists (f_test) then
begin
let ic = open_in f_test in
try
let try_read () =
try Some (input_line ic) with End_of_file -> None in
let rec loop acc = match try_read () with
| Some s -> loop (s :: acc)
| None -> close_in_noerr ic; List.rev acc in
loop []
with e ->
close_in_noerr ic;
[]
end
else
[]
;;
(*Using Records*)
type user =
{
name : string;
age : int;
country : string;
};;
(*
Function to separated info in list
*)
let rec splitinfo ?(sep=":") l = match l with
| [] -> []
| x::xs -> (Str.split (Str.regexp ":") x)::splitinfo xs;;
(*
Function to get users position
*)
let get_user l:user =
let age = int_of_string (List.nth l 1) in
let user_name = List.nth l 0 in
{
name = user_name;
age = age ;
country = List.nth l 2;
};;
(*
Function to check some parameter is valid
*)
let par1 u: int =
if (u.age = 3) then
1
else
0;;
(*
Reporting function
*)
let report_statistics list_users =
let child = ref 0 in
let teenager = ref 0 in
let adult = ref 0 in print_string (" ----- -- Stats -- ----- \n" ) ;
List.iter (
fun user_l -> (
match user_l with
| [] -> print_string("> no user <\n")
| _ ->
let user = get_user user_l in
if (par1 user = 1) then (
print_string (" "^ user.name ^" --> Child \n" ) ;
child := !child + 1;
)
else
print_string (" "^ user.name ^" --> Other \n" );
)
) list_users;
print_string ("------- List ---- ");
print_newline();
print_string ("Child " );
print_int(!child);
print_newline();
print_string ("Teenager ") ;
print_int(!teenager);
print_newline();
print_string ("Adult ");
print_int(!adult);
print_newline();
;;
The program compile but doesn't output any result ...
What am i missing ?
I kept the function to check parameters simple so i can understand it better but can't figure it out why it isn't outputing any result
Can you help me out here ?
Thanks in advance :)
The code as given defines some functions such as read_lines and report_statistics. But there are no calls to these functions.
If there is no other OCaml source involved, this is probably your problem. You need to call the functions.
It is fairly customary to have a "main" function that does the work of an OCaml program, and then (this is key) you have to actually call the main function:
let main () =
(* Call the functions that do the work of the program *)
let () = main ()
I have many times forgotten this last line and then nothing happens when I run the program.
I wonder if it is possible in OCaml to use one field of record in the other field in the same record.
Basicaly, I have field with function in which I would like to use also other, values, fields of the same record so when the value change the function will use the new value.
I can do it with setting the function field mutable and update it after the record is created e.g.
type 'a cell =
{ mutable value: 'a
; mutable fn: unit -> 'a }
let create_cell ~(value : 'a) : 'a cell =
let c = {value; fn= (fun () -> value + 42)} in
let _ = c.fn <- (fun () -> c.value + 42) in
c
I was wondering if it is possible without fn field being mutable and in one go.
You can use let rec to make the function refer to the record it is part of:
# type 'a cell = { mutable value : 'a ; fn : unit -> 'a };;
type 'a cell = { mutable value : 'a; fn : unit -> 'a; }
# let rec r = { value = 14; fn = fun () -> r.value + 14 };;
val r : int cell = {value = 14; fn = <fun>}
# r.fn ();;
- : int = 28
# r.value <- 10;;
- : unit = ()
# r.fn ();;
- : int = 24
If I understand correctly, this what you'd like to do.
So then your create_cell function might look like this:
let create_cell ~(value : 'a) : 'a cell =
let rec c = {value; fn= (fun () -> c.value + 42)} in
c
It seems to work:
# let mycell = create_cell ~value: 88;;
val mycell : int cell = {value = 88; fn = <fun>}
# mycell.fn ();;
- : int = 130
# mycell.value <- 100;;
- : unit = ()
# mycell.fn ();;
- : int = 142
How do you do, Stackoverflow!
In Java practice there are some issues concerning partially defined functions. Sometimes it's convinient to separate an error handling from the calculation itself. We may utilize an approach called "Guard types" or "Guard decorators".
Consider the simple synthetic example: to guard the null reference. This can be done with the aid of the next class
public class NonNull<T> {
public take() {
return null != this.ref ? this.ref : throw new ExcptionOfMine("message");
}
public NotNull(T ref_) {
this.ref = ref_;
}
private T ref;
}
The question is:
Is there a way to implement the same "Guard type" in OCaml without touching its object model? I believe for the OCaml as the functional programming language to possess enough abstraction methods without objec-oriented technics.
You can use an abstract type to get the same effect. OCaml has no problem with null pointers. So say instead you want to represent a nonempty list in the same way as above. I.e., you want to be able to create values that are empty, but only complain when the person tries to access the value.
module G :
sig type 'a t
val make : 'a list -> 'a t
val take : 'a t -> 'a list
end =
struct
type 'a t = 'a list
let make x = x
let take x = if x = [] then raise (Invalid_argument "take") else x
end
Here's how it looks when you use the module:
$ ocaml
OCaml version 4.02.1
# #use "m.ml";;
module G :
sig type 'a t val make : 'a list -> 'a t val take : 'a t -> 'a list end
# let x = G.make [4];;
val x : int G.t = <abstr>
# G.take x;;
- : int list = [4]
# let y = G.make [];;
val y : '_a G.t = <abstr>
# G.take y;;
Exception: Invalid_argument "take".
There's a concept of Optional types, on which you can effectively pattern match. Example:
let optional = Some 20
let value =
match optional with
| Some v -> v
| None -> 0
You can use simple closures
let guard_list v =
fun () ->
if v = [] then failwith "Empty list"
else v
let () =
let a = guard_list [1;2;3] in
let b = guard_list [] in
print_int (List.length (a ())); (* prints 3 *)
print_int (List.length (b ())) (* throws Failure "Empty list" *)
or lazy values
let guard_string v = lazy begin
if v = "" then failwith "Empty string"
else v
end
let () =
let a = guard_string "Foo" in
let b = guard_string "" in
print_endline (Lazy.force a); (* prints "Foo" *)
print_endline (Lazy.force b) (* throws Failure "Empty string" *)
The doc of Lazy.lazy_from_val states that this function is for special cases:
val lazy_from_val : 'a -> 'a t
lazy_from_val v returns an already-forced suspension of v This is for special purposes only and should not be confused with lazy (v).
Which cases are they talking about?
If I create a pair of suspended computation from a value like:
let l1 = lazy 123
let l2 = Lazy.lazy_from_val 123
What is the difference between these two? Because Lazy.lazy_is_val l1 and Lazy.lazy_is_val l2 both return true saying that the value is already forced!
The special purpose would be if you need a lazy value but you sometimes have an already computed (non-lazy) value. You can use lazy_from_val to turn an already computed value into a (forced) lazy version of your value.
let f lazyint =
Lazy.force lazyint + 42
let li = lazy 4;;
# f li;;
- : int = 46
# f 14;;
^^
Error: This expression has type int but an expression was expected of type
int Lazy.t = int lazy_t
# f (Lazy.lazy_from_val 14);;
- : int = 56
In this (contrived) example, you might wish to call f with an ordinary integer value (14, in this example). You can do it, but you need to use Lazy.lazy_from_val to make it work.
The key difference is that lazy takes an expression of type 'a and creates a suspended computation (in essence, a closure) of type 'a lazy_t. Lazy.lazy_from_val takes a pre-computed value of type 'a and converts it to a (pre-forced) value of type 'a lazy_t. If the expression has side-effects, the difference between the two can be seen.
# let p () = print_string "here\n"; 3 ;;
val p : unit -> int = <fun>
# let l1 = lazy (p ());;
val l1 : int lazy_t = <lazy>
# let l2 = Lazy.lazy_from_val (p ());;
here
val l2 : int Lazy.t = lazy 3
# f l1;;
here
- : int = 45
# f l2;;
- : int = 45
#
You could implement lazy operations directly using explicit closures and references. As Matthias Benkard points out, OCaml's lazy mechanism uses special syntax to make it less cumbersome to work with. I.e., lazy is an OCaml keyword, not a function.
lazy_from_val is a function rather than syntax. Thus,
# let id = fun x -> x;;
val id : 'a -> 'a = <fun>
# Lazy.lazy_is_val (lazy (id 123));;
- : bool = false
# Lazy.lazy_is_val (Lazy.lazy_from_val (id 123));;
- : bool = true
i'm trying to learn ocaml right now and wanted to start with a little program, generating all bit-combinations:
["0","0","0"]
["0","0","1"]
["0","1","0"]
... and so on
My idea is the following code:
let rec bitstr length list =
if length = 0 then
list
else begin
bitstr (length-1)("0"::list);
bitstr (length-1)("1"::list);
end;;
But i get the following error:
Warning S: this expression should have type unit.
val bitstr : int -> string list -> string list = <fun>
# bitstr 3 [];;
- : string list = ["1"; "1"; "1"]
I did not understand what to change, can you help me?
Best regards
Philipp
begin foo; bar end executes foo and throws the result away, then it executes bar. Since this makes only sense if foo has side-effects and no meaningful return value ocaml emits a warning if foo has a return value other than unit, since everything else is likely to be a programmer error (i.e. the programmer does not actually intend for the result to be discarded) - as is the case here.
In this case it really does make no sense to calculate the list with "0" and then throw it away. Presumably you want to concatenate the two lists instead. You can do this using the # operator:
let rec bitstr length list =
if length = 0 then
[list]
else
bitstr (length-1)("0"::list) # bitstr (length-1)("1"::list);;
Note that I also made the length = 0 case return [list] instead of just list so the result is a list of lists instead of a flat list.
Although sepp2k's answer is spot on, I would like to add the following alternative (which doesn't match the signature you proposed, but actually does what you want) :
let rec bitstr = function
0 -> [[]]
| n -> let f e = List.map (fun x -> e :: x) and l = bitstr (n-1) in
(f "0" l)#(f "1" l);;
The first difference is that you do not need to pass an empty list to call the function bitsr 2 returns [["0"; "0"]; ["0"; "1"]; ["1"; "0"]; ["1"; "1"]]. Second, it returns a list of ordered binary values. But more importantly, in my opinion, it is closer to the spirit of ocaml.
I like to get other ideas!
So here it is...
let rec gen_x acc e1 e2 n = match n with
| 0 -> acc
| n -> (
let l = List.map (fun x -> e1 :: x) acc in
let r = List.map (fun x -> e2 :: x) acc in
gen_x (l # r) e1 e2 (n - 1)
);;
let rec gen_string = gen_x [[]] "0" "1"
let rec gen_int = gen_x [[]] 0 1
gen_string 2
gen_int 2
Result:
[["0"; "0"]; ["0"; "1"]; ["1"; "0"]; ["1"; "1"]]
[[0; 0]; [0; 1]; [1; 0]; [1; 1]]