Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml checking functions

Tags:

ocaml

I want to define a function check_char_fun: (char -> 'a) -> (char ->' a) -> bool that, given two functions on char, return true when both functions are the same (ie, when they are exactly the same behavior on every one of the possible values of a char) and false otherwise.

let check_char_fun f1 f2 =
let aux = true
for i=0 to 255 do
    if (f1 (char_of_int i))=(f2 (char_of_int i))
    then aux=false;
done;
if aux=true
then true
else false;;

I am learning OCaml, so I don't know what can I do.

like image 937
Chen Yo Avatar asked Apr 22 '26 18:04

Chen Yo


1 Answers

You're nearly there:

let check_char_fun f1 f2 =
  let aux = ref true in
  for i = 0 to 255 do
    if (f1 (char_of_int i)) = (f2 (char_of_int i)) then aux := false
    else ()
  done;
  !aux

Unlike the variables in imperative languages, bindings in OCaml are immutable by default. To create a real variable, we create a bool ref which is mutable and can be changed from within the loop.

OCaml does not have a distinction between statements and expressions like the imperative languages: There are only expressions! Thats why you always need the else clause to an if; this ways the resulting expression always returns a value (in both if and else case) the type of which must be the same -- in this case of type unit (the type of the value () -- which would be void in C).

Your code is not very OCaml-like, but thats what I personally love about OCaml: The functional style is not forced down your throat and you can implement algorithms in an imperative style without entering the academic ivory tower.

like image 131
lambdapower Avatar answered Apr 28 '26 18:04

lambdapower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!