F # Tutorial: anonymous function (LAMBDA)

Source: Internet
Author: User
Tags anonymous expression

This time we're going to learn about lambda expressions. F # and C # have anonymous functions as well. But it feels better to call an anonymous function a lambda.

Try writing some code:

let add = fun x y -> x + y
printfn "%A" (add 1 3)

Here we define the Add function. This definition uses an anonymous function (takes out the x,y two parameters and returns the x+y result). Fun is the key word for anonymous functions.

The function definitions that you have before are:

Let add x y = x + y

This is an elliptical form. The difference is whether the parameter is in a lambda expression.

From the experience of C #, you can pass functions as arguments to other functions.

let add = fun x y -> x + y
let hoge func =
     let a = func 1 10
     printfn "%A" a
hoge add  // 将add作为参数传入hoge函数中

Yes, it does, the result is 11.

Of course, you can also try to pass the lambda expression directly into the previous function.

let hoge func =
     let a = func 1 10
     printfn "%A" a
hoge (fun x y -> x + y)  // 直接传入lambda表达式

Lambda expressions are commonly used in c#3.0, which makes it less strange to use Lambda in F #.

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.