2018-08-02 22:04:49 +03:00
|
|
|
|
<html>
|
|
|
|
|
|
|
|
|
|
|
|
<head>
|
|
|
|
|
|
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e">
|
2025-11-07 16:12:31 +03:00
|
|
|
|
<param name="Keyword" value="Захват переменных в лямбда-выражении">
|
2018-08-02 22:04:49 +03:00
|
|
|
|
</object>
|
|
|
|
|
|
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
|
|
|
|
|
|
<title></title>
|
|
|
|
|
|
<link rel="StyleSheet" href="../../default.css">
|
|
|
|
|
|
</head>
|
|
|
|
|
|
|
|
|
|
|
|
<body>
|
2025-11-07 16:12:31 +03:00
|
|
|
|
<H1>Захват переменных в лямбда-выражении</H1>
|
|
|
|
|
|
<p><a href="lambdas.html">Лямбда-выражение</a> может использовать переменные из
|
|
|
|
|
|
внешнего контекста. Такие переменные называются захваченными лямбда-выражением.</p>
|
|
|
|
|
|
<p><strong>Пример 1.</strong> Захват переменной в запросе Select.</p>
|
2018-08-02 22:04:49 +03:00
|
|
|
|
<blockquote><code><strong>begin</strong><br> <strong>var</strong> a :=
|
|
|
|
|
|
Seq(2,3,4);<br> <strong>var</strong> z := 1;<br> <strong>var</strong>
|
|
|
|
|
|
q := a.Select(x->x+z);<br> q.Println;<br> z := 2;<br>
|
|
|
|
|
|
q.Println;<br><strong>end</strong>.</code></blockquote>
|
2025-11-07 16:12:31 +03:00
|
|
|
|
<p>Здесь лямбда-выражение <code>x->x+z</code> захватывает внешнюю переменную z.
|
|
|
|
|
|
Важно заметить, что при изменении значения переменной z запрос <code>
|
|
|
|
|
|
a.Select(x->x+z)</code>, хранящийся в переменной q, выполняется с новым
|
|
|
|
|
|
значением z.</p>
|
|
|
|
|
|
<p><strong>Пример 2.</strong> Накопление суммы во внешней переменной.</p>
|
2018-08-02 22:04:49 +03:00
|
|
|
|
<blockquote><code><strong>begin</strong><br> <strong>var</strong> sum :=
|
|
|
|
|
|
0;<br> <strong>var</strong> AddToSum: integer -> () := <strong>
|
|
|
|
|
|
procedure</strong> (x) -> <strong>begin</strong> sum += x; <strong>
|
|
|
|
|
|
end</strong>;<br><br> AddToSum(1);<br> AddToSum(3);<br>
|
|
|
|
|
|
AddToSum(5);<br><br> writeln(sum); <br><strong>end</strong>.</code></blockquote>
|
|
|
|
|
|
<p> </p>
|
|
|
|
|
|
</body>
|
|
|
|
|
|
|
|
|
|
|
|
</html>
|