lambda A lambda expression is composed of three
lambda
A lambda expression is composed of three parts. Argument List Arrow Token Body (int x, int y) -> x+y
Lambda functions • canvas. set. On. Mouse. Entered((a) -> System. out. println("hi")); • canvas. set. On. Mouse. Pressed((a) -> System. out. println("focus")); canvas. set. On. Key. Released(new Event. Handler<Key. Event>() { @Override public void handle(Key. Event event) { System. out. println("Handled"); } });
// with no parameter () -> System. out. println("Hello, world. ") // with one parameter (this example is an identity function). a -> a // with one expression (a, b) -> a + b // with explicit type information (long id, String name) -> "id: " + id + ", name: " + name // with a code block (a, b) -> { return a + b; }
// with multiple statements in the lambda body. It needs a code block. // This example also includes two nested lambda expressions (the first one is also a closure). (id, default. Price) -> { Optional<Product> product = product. List. stream(). filter(p -> p. get. Id() == id). find. First(); return product. map(p -> p. get. Price()). or. Else(default. Price); }
Alus: lambda-arvutus Lambda-arvutuse keel on Alonzo Churchi poolt 1930. aastatel leiutatud lihtne ja universaalne meetod funktsioonide kirjapanekuks. Lambda-arvutuse teooria tegeleb arvutatavuse ja arvutatavate funktsioonide uurimisega, kasutades selleks lambda-arvutuse keelt kui universaalset programmeerimiskeelt. Churchi tees väidab, et iga algoritmi saab lambda-arvutuse keeles kirja panna. On võimalik näidata, et lambda-arvutus, nagu ka Prolog, C ja Basic on üks paljudest universaalsetest programmeerimiskeeltest. Konkreetselt on lambda-arvutuse keel ja teooria funktsionaalsete programmeerimiskeelte aluseks.
Example 1: Print a list of integers with a lambda List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each(x -> System. out. println(x)); • x -> System. out. println(x) is a lambda expression that defines an anonymous function with one parameter named x of type Integer
Example 2: A multiline lambda List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each(x -> { x += 2; System. out. println(x); }); • Braces are needed to enclose a multiline body in a lambda expression.
Example 3: A lambda with a defined local variable List<Integer> int. Seq = Arrays. as. List(1, 2, 3); int. Seq. for. Each(x -> { int y = x * 2; System. out. println(y); }); • Just as with ordinary functions, you can define local variables inside the body of a lambda expression
- Slides: 9