OCaml Primer (5)

Source: Internet
Author: User
Tags ocaml

anonymous functions

In a functional language, a function is a class citizen, and it should be able to support "literal" like other types (int,float,string, etc.), which is the anonymous function.

1 );; int int = <fun>17;; int 8

As you can see, anonymous functions can be used instead of the function's location.

Some functions require an argument that is another function, but can also be passed in with an anonymous function. Like what:

Utop # List.map ~f: (Fun x->x+1) [1;  2; 3 ];; int list = [234]

Don't worry too much: ~f: This syntax, this is just the use of a named function call. In most languages, functions are called by location to match parameters.

The disadvantage of this is that it is easy to forget which parameter is in which position. OCaml Of course also supports the method of calling functions by location, but also encourages the invocation of functions by name, so that the program is more readable.

(You might think it's a little awkward, just endure, people tend to be slaves of habit)

An anonymous function can of course bind to a symbol, which becomes a named function:

1intint = <fun>    5;; int 6   

This definition is so common that OCaml provides syntactic sugars to simplify:

1intint = <fun>  

This is exactly the same as the previous definition, except that the syntax is lazy.

An anonymous function can also have multiple parameters:

Utop # let diff x y = abs (X-intint int = <fun>  58;; int 3   

You might be surprised. The type signature of this function: int, int, int

In our imagination, it should be: int, int is more reasonable.

This is one of the more mathematical features of functional languages. Mathematically, strictly speaking, each function can only pass in one parameter and return a parameter.

If a function appears to pass in two arguments, it is simply a function that passes in one parameter and returns another function.

In other words, in essence, the upper function definition is equivalent to:

Utop # Let diff =-(Fun y-abs (X-intint int = <fun>  

This is a mental gymnastics, think carefully.

The power of a functional language is that functions can be used as parameters, and functions can be used as return values.

According to this idea, we can naturally write:

3intint = <fun>  8;; int 5     

For multi-parameter functions, it is common to provide only partial parameters, which are mathematically referred to as: the partial parameter function.

Recursion of functions

The functional language does not encourage (or even disallow) the use of variable + looping programming patterns, which are more preferred to "recursion" than loops.

Recursion is a function that calls itself directly or indirectly.

Utop # let rec len lst = match lstwith 01 +'a list--int = <fun> ;     Utop # len [1;  2; 3; 4 ];; int 4       utop # len [];; int 0  

If a function is recursive, the OCaml requirement must be explicitly modified with Rec.

REC is the abbreviation for recursive.

If indirect recursion is required to define multiple functions at once, such as: Is_even to determine whether an even number. This is just a demonstration of the concept, of course, only for this small function is not necessary so much trouble.

Utop # Let rec is_even x =ifx=0Thentrue ElseIs_odd (x1) and is_odd x=ifx=0Thenfalse ElseIs_even (x1);; Val Is_even:int-BOOL= <fun>val is_odd:int-BOOL= <fun>Utop # Is_even7;;- :BOOL=falseUtop # Is_even8;;- :BOOL=true 
Prefixes and infix

The general function call is the prefix format: function parameter parameter ...

Sometimes, when two parameters, infix more in line with the habit. Example: 1 + 2, 5 mod 3

In OCaml, functions and operators are the same thing: function

If you add parentheses to the infix operator, you return to the prefix style:

 Utop # (+) 8  ;; -: int  = 13   Utop # (MoD)  10  ;;  -: int  = 1   Utop # list.map  ~f: ((+) 1 ; 2 ; 3 ; 4   -: int  list = [4 ; 5 ; 6 ; 7 ] 

It is also possible to define the infix operator yourself, which must be combined from the following set of symbols:

! $% & * +-. /: < = >? @ ^ | ~
Like what:
Utop # Let (+!) (x1,y1) (x2,y2) = x1+x2, y1+int int int int. Int. INT = <fun> utop # (1,2) +! (ten); int int = (each)

Using an operator with * requires extra care, because (* ...). *) represents a comment statement.

3 5 ;; int  the  

The space between the brackets and the asterisk is a must!

Function

Let ff x = Match x with ... | ... | ...

This pattern is so common that OCaml provides a further simplification of the syntax:

Utop # Let Len = function01 +'a list, int = <fun>     utop # len [1;  2];; int 2  
Label parameters

Multi-parameter functions can use label parameters to increase readability and flexibility.

The following function asks for a slope.

1.0 4 inch  180.0 /. Pi;; Val po:path: float, height:floatfloat = <fun>~path: . ~height:1.;; float 5.73917047727  

Since the parameters are also named, the order is irrelevant.

Utop # PO ~height:1. ~path:ten.; float 5.73917047727  

OCaml Primer (5)

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.