Jiang Y
Jiang Y

Reputation: 3

Ocaml - redefine a function inside a new function

Sorry I'm not sure how to give a proper title for this problem: If I do:

 let f1= function 1 -> failwith "a" | s ->s;;(*you can just use f1 x=x, just want to let f1 to have an exception case*)
 let f2 = 
     let f1= 
           try(print_string "s1";f1) 
           with _ -> (print_string "s2" ;failwith "s3") 
     in 
     let conv tm = f1 tm 
     in conv;;
 let f3 = 
     let conv tm = 
         let f1= 
             try(print_string "s1";f1) 
             with _ -> (print_string "s2" ;failwith "s3") 
         in 
         f1 tm 
     in conv;;
  1. We can notice that "s1" is already printed while defining f2 (after loading this funcion), which means the new f1 is already excuted while loading f2
  2. If we try f2 1 and f3 1, only f3 1 will print "s1".
  3. Neither f2 nor f3 print "s2" when exception occurs

Now I'm a little confused about what's going on. f1 was actually redefined, even in f2, because if we do

let f4 = 
     let f1= ()
     in 
     let conv tm = f1 tm 
     in conv;;

An error for type checking will occur.

  1. I don't know the difference between f2 and f3, because f1 is redefined before conv anyway.
  2. Why in f3, even "s1" is printed, "s2" is not printed as I expected?

I'm using ocaml 4.01.0

Upvotes: 0

Views: 157

Answers (1)

Bergi
Bergi

Reputation: 664528

The exception is only thrown when f1 is actually called. However, you don't call it inside the try block - in either f2 or f3 - you just evaluate the reference there and assign the return value to your local f1 variable. The actual call which will cause the exception is always f1 tm.

You seem to be looking for

let f4 tm = try
              print_string "s1";
              f1 tm
            with
              _ -> print_string "s2";
                   failwith "s3";;

Upvotes: 1

Related Questions