खोज…


सरल लंबोदर भाव

// A simple adder function defined as a lambda expression. 
// Unlike with regular functions, parameter types often may be omitted because the
// compiler can infer their types
let adder = |a, b| a + b;
// Lambdas can span across multiple lines, like normal functions.
let multiplier = |a: i32, b: i32| {
    let c = b;
    let b = a;
    let a = c;
    a * b
};

// Since lambdas are anonymous functions, they can be called like other functions
println!("{}", adder(3, 5));
println!("{}", multiplier(3, 5));

यह प्रदर्शित करता है:

8
15

साधारण बंद

नियमित कार्यों के विपरीत, लैम्ब्डा अभिव्यक्ति उनके वातावरण पर कब्जा कर सकते हैं। ऐसे लंबोदर को क्लोजर कहा जाता है।


// variable definition outside the lambda expression...
let lucky_number: usize = 663;

// but the our function can access it anyway, thanks to the closures
let print_lucky_number = || println!("{}", lucky_number);

// finally call the closure
print_lucky_number();

यह प्रिंट करेगा:

663

स्पष्ट वापसी प्रकार के साथ लम्बदा

// lambda expressions can have explicitly annotated return types
let floor_func = |x: f64| -> i64 { x.floor() as i64 };

चारों ओर से लंबोदर गुजर रहे हैं

चूंकि लैम्ब्डा फ़ंक्शंस स्वयं मान हैं, आप उन्हें संग्रह में संग्रहीत करते हैं, उन्हें फ़ंक्शंस में पास करते हैं, जैसे आप अन्य मूल्यों के साथ।

// This function takes two integers and a function that performs some operation on the two arguments
fn apply_function<T>(a: i32, b: i32, func: T) -> i32 where T: Fn(i32, i32) -> i32 {
    // apply the passed function to arguments a and b
    func(a, b)
}

// let's define three lambdas, each operating on the same parameters
let sum = |a, b| a + b;
let product = |a, b| a * b;
let diff = |a, b| a - b;

// And now let's pass them to apply_function along with some arbitary values
println!("3 + 6 = {}", apply_function(3, 6, sum));
println!("-4 * 9 = {}", apply_function(-4, 9, product));
println!("7 - (-3) = {}", apply_function(7, -3, diff));

यह प्रिंट करेगा:

3 + 6 = 9
-4 * 9 = -36
7 - (-3) = 10

कार्यों से लौटते हुए लंबोदर

कार्यों से लौटते हुए लंबोदर (या बंद) मुश्किल हो सकते हैं क्योंकि वे लक्षण लागू करते हैं और इस प्रकार उनके सटीक आकार को शायद ही कभी जाना जाता है।

// Box in the return type moves the function from the stack to the heap
fn curried_adder(a: i32) -> Box<Fn(i32) -> i32> {
    // 'move' applies move semantics to a, so it can outlive this function call
    Box::new(move |b| a + b)
}

println!("3 + 4 = {}", curried_adder(3)(4));

यह प्रदर्शित करता है: 3 + 4 = 7



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow