• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

DevLog 20250510 Dealing with Lambda

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
The essence of lambda calculus is with captures - be it simple values or object references, at the site of anonymous function declaration, it's being captured and (the reference) is saved inside the lambda until being invoked.


// C# – capturing a local variable in a LINQ query
int factor = 3;
int[] numbers = { 1, 2, 3, 4, 5 };
var scaled = numbers
.Select(n => n * factor) // ‘factor’ is captured from the enclosing scope
.ToArray();
Console.WriteLine(string.Join(", ", scaled)); // 3, 6, 9, 12, 15

In C++ this is more explicit and the capturing process is more obvious:


// C++20 – capturing a local variable in a ranges pipeline
#include <iostream>
#include <vector>
#include <ranges>

int main() {
int factor = 3;
std::vector<int> numbers = { 1, 2, 3, 4, 5 };

// capture ‘factor’ by value in the lambda
auto scaled = numbers
| std::views::transform([factor](int n) { return n * factor; });

for (int x : scaled)
std::cout << x << " "; // 3 6 9 12 15
}

What happens when an object reference is disposed, as in the case of IDisposable? It will simply throw an error.


using System;
using System.IO;

class Program
{
static void Main()
{
// Create and use a MemoryStream
var ms = new MemoryStream();
ms.WriteByte(0x42); // OK: writes a byte

// Dispose the stream
ms.Dispose(); // Unmanaged buffer released, internal flag set

try
{
// Any further operation is invalid
ms.WriteByte(0x24); // <-- throws ObjectDisposedException
}
catch (ObjectDisposedException ex)
{
Console.WriteLine($"Cannot use disposed object: {ex.GetType().Name}");
}
}
}


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



An important distinction is events or plain callbacks that requires no return value, which can be implemented quite plainly.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



To achieve the same thing in dataflow context, some kind of GUI (or "graph-native") support is needed, and to the taker/caller, it's evident (in the language of C#) it's taking a delegate as argument.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




public static System.Collections.Generic.IEnumerable<TResult> Select<TSource,TResult>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int,TResult> selector);

To implement capturing, the most natural way is to make sure it happens "in-place" - directly on the graph. With this handy, we do not need to implement specialized nodes for all kinds of functions and instead can rely on existing language construct to do the rest.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



The last bit is actually inspired by Haskel, where functions are first class and we can do composition on functions:


-- A simple two‑argument function
add :: Int -> Int -> Int
add x y = x + y

-- Partially apply 'add' to “capture” the first argument
addFive :: Int -> Int
addFive = add 5

main :: IO ()
main = do
print (addFive 10) -- 15
print (map (add 3) [1,2,3]) -- [4,5,6]


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу