In chapter 2 of OCaml from the very beginning, I learned the following:
Naming an expression
- Use the following constructs to define our own name (e.g., x) to stand for the result of evaluating an expression:
- let x = (expression) ;;
- let x = (expression) in (another expression) ;;
- OCaml replies to confirm that an expression x is named, and confirm its type and value. E.g., let x = 200 ;; :
val x : int = 200
Naming a function
- Use the following construct to define a function (e.g. cube) that takes an argument (e.g. x), and applies it to the function as defined:
- let cube x = x * x * x ;;
- OCaml replies to confirm that a function cube is named, and confirm the type of the argument(s) it takes, and the type of the value the function evaluates to:
val cube : int -> int : <fun>
Naming a recursive function
- A recursive function is a function which uses itself. That is, when we define such a function, its own function name has to be in the function definition.
- Use the following construct to define a recursive function (e.g. factorial) that takes an argument, and applies it to the function as defined:
- let rec factorial x =
if x = 1 then 1 else factorial (x – 1) * x ;;
- let rec factorial x =
- OCaml replies similarly to when a function is defined, telling us the types of the argument(s) and the value the function evaluates to:
val factorial : int -> int = <fun>
- Make sure that any recursive function you define terminates. Check that you have given the recursive function a way to terminate in all cases of the appropriate type of the argument(s).
- OCaml has a built-in function named not. not takes an argument of type bool and returns a value of type bool. That is, when you type ‘not’ in OCaml, it replies with:
– : bool -> bool = <fun>
Leave a Reply