Ocaml programming speed Overview

Source: Internet
Author: User
Tags ocaml

Once you understand ocaml, you will feel that it is a very magical language, but the first step is very difficult to learn it. I hope this small tutorial will make things easier.
First, ocaml is not a structured language and belongs to the function language family. Pure function language does not provide a Loop Mechanism (you need to use recursion to complete the loop), variables cannot be changed, and other restrictions. Fortunately, ocaml is not a pure function language, so you can use loops and change variables. Now let's start the adventure of ocaml :)

First, let's start ocaml and input ocaml at the command prompt. You will see the following content:

  1. Objective caml version 3.04
  2. #

Copy code

# Is the ocaml interpreter prompt. We have started it.

Type

Ocaml is a strongly typed language. This indicates that once a variable is created, the type cannot be changed, and you cannot perform operations between two different types (such as adding integers and floating-point numbers ). Let's make some basic mathematical calculations:

  1. #2 + 2 ;;
  2. -: Int = 4

Copy code

';' Is the end of an expression, which is similar to the end of a sentence. The second row displays the result and result type (INT ). I have said that different types of computing cannot be mixed. Let's see what will happen in this case:

  1. #2 + 2.5 ;;
  2. This expression has type float but is here used with type int

Copy code

You will see an underline under 2.5 (I cannot underline the number here) and get the error message in the second line. What does it tell you? It tells you that your function can only operate integers, but 2.5 is a floating point number. So how can we add floating point numbers? For floating point calculation, we use the operator +. (add a bit after the plus sign, that is, the floating point operator ). Let's try again. Use the operator + this time.

  1. #2 +. 2.5 ;;
  2. This expression has type int but is here used with Type Float

Copy code

Now the underline goes down to 2, and ocaml tells you that you use an integer in the floating point operator. How can we get their sum? We need to convert one of the number types in the expression to another type. Here, if we convert 2.5 to an integer, we will lose. 5 (this may not be the result we want), so we will convert 2 to a floating point number.

  1. # (Float_of_int 2) +. 2.5 ;;
  2. -: Float = 4.5

Copy code

What is float_of_int? Let ocaml answer our questions!

  1. # Float_of_int ;;
  2. -: Int-> float = <fun>

Copy code

In the above expression, O' caml will tell us that float_of_int is a function (<fun>) that receives an integer parameter and returns a floating point value. So when we pass 2 to float_of_int, it returns 2.0, so that we can calculate it.
Remember that only values of the same type can work together.

Integer Arithmetic Operator:
+: Add
-: Minus
*: Multiplication
/:
MoD: modulo

Floating Point OPERATOR:
+.: Add
-.: Minus
*.: Multiplication
/.:
**: Power

Convert integer to floating point: float_of_int n
Convert floating point to integer: int_of_float n

Function Definition
In ocaml, like other strong-type languages, a function gets a parameter of a predefined type and returns a value of a given type. Function parameters are separated by spaces.
If we want to define the following functions, their mathematical form is:

Double: X-> 2x
Square: X-> X * x
Cube: X-> x ^ 3

How can we implement them in ocaml:

  1. # Let double = fun X-> 2. *. X ;;
  2. # Let square = fun X-> X *. X ;;
  3. # Let cube = fun X-> X ** 3 .;;

Copy code

From the above syntax, we can see that the part that really defines a function starts with "fun. The previous "Let double =" is the name of the function. You can also use a function without a name in ocaml. Another syntax can be used to define a function:

  1. # Let Double X = 2. *. X ;;
  2. # Let square x = x *. X ;;
  3. # Let cube x = x ** 3 .;;

Copy code

Note the point after. It tells the compiler function to accept only floating-point parameters (so it also returns a floating point ). For the Function Square, if this vertex function is not provided after the * sign, only integer parameters are accepted. This process of inferring types based on the syntax used by the function is called type inference. This makes the code easier to read. To avoid misunderstanding, the ocaml translator always tells you the type it exports. In the following example, I will omit the input information.

The function is of the first-class type.
This is the most interesting feature in ocaml. functions are of the first-class type. More specifically, they can be passed to another function and can be of any general type (such as integer, floating point, string) returned.
Let's explain it through an example. Suppose we want to define a function composed of two functions F and G. The mathematical definition is as follows:

F o G: X-> (f o g) (x) = f (g (x ))

In ocaml, this is very simple:

  1. Let compose f g = fun X-> F (g (x ));;

Copy code

If you are careful enough, you will notice several things:
1. The syntax is very similar to the previous mathematical definition.
2. We do not need to pass X as a variable to the compose function. We only need to pass F and G as parameters to the compose function. The ocaml type checker exports F and G according to the syntax X-> F (g (x. Here, X is a virtual variable called a constraint variable.

3. The comopse function actually returns a function, which is a combination of F and G, as we will see below:

  1. # Compose double square 3 .;;
  2. -: Float = 18.
  3. # Compose square double 3 .;;
  4. -: Float = 36.
  5. (* Define a combination of functions that divide parameters by 2 *)
  6. # Let myfunc = compose square (fun X-> X/. 2 .);;
  7. # Myfunc 5 .;;
  8. -: Float = 6.25

Copy code

Here, I define the function myfunc as a combination of the square function and an unnamed function that divides the input parameter 2.

Let's write the example as follows to show the compose return function:

  1. (* Define a composite with a function that divides its input by 2 *)
  2. # Let myfunc F = compose square f ;;
  3. # Myfunc (fun X-> X/. 2.) 5 .;;
  4. -: Float = 6.25

Copy code

Symbolic
The compose function can be defined as an infix operator. The operator may not contain letters. To use it as an infix, place it between brackets. As follows:

  1. (* Define the infix operator composite *)
  2. # Let (@) = compose ;;
  3. # (Double @ square) 3 .;;
  4. -: Float = 18.
  5. # (Square @ double) 3 .;;
  6. -: Float = 36.

Copy code

Q: Why do square @ double need parentheses?

Function chain Processing
A chain is a standard data structure in function languages. Using the standard library list. Map allows functions to process all elements in a chain without loops. For example:

  1. (* Create a list of floats *)
  2. # Let V = [1.; 2.; 3.; 4.; 5.];
  3. # List. Map (myfunc @ square) V ;;
  4. -: Float list = [0.25; 4.; 20.25; 64.; 156.25]

Copy code

To avoid writing list. map every time, you can rewrite the Code as follows:

  1. (* These new functions take a list of floats as their input and return a list of floats *)
  2. # Let square = fun V-> list. Map (fun X-> X *. X) V ;;
  3. # Let myfunc = fun V-> list. Map (square @ (fun X-> X/. 2.) V ;;
  4. # (Myfunc @ square) V ;;
  5. -: Float list = [0.25; 4.; 20.25; 64.; 156.25]

Original: http://bbs.9ria.com/thread-77807-1-1.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.