Skip to content

Latest commit

 

History

History
49 lines (43 loc) · 1.84 KB

221030.lambdas.md

File metadata and controls

49 lines (43 loc) · 1.84 KB

2022-10-30

https://discordapp.com/channels/918498540232253480/918498540232253483/1036427638715203656

bmentink

Hi, can someone elaborate on the syntax for the following mqtt.Client code, I am not sure how this starts as a task, as anormal task is started with task:: and all I see here is ::

client = mqtt.Client --transport=transport --routes={
      TOPIC: :: | topic payload |
        // Do something with topic and payload
    }

floitsch

This, by itself, doesn't start a task yet.
All this does, is tell the client that it should route messages to TOPIC to the lambda (:: | topic payload | ...).
The task is only created when you call client.start.

bmentink

Got it: I stiil don't understanf what a lambda is ..

floitsch

That task then receives messages, and then uses the routes-map to dispatch incoming messages accordingly.
A lambda is a function of JavaScript.
In C++ this would be a [&]() { ... }
(although better than that, as it the variables it refers to are kept alive, whereas C++ would barf).

bmentink

So it's a pointer to function of code ..

floitsch

In Python anonymous functions are actually called "lambda" too.
Pretty much.
The :: print "foo" becomes an object that has a call method that then executes the code print "foo".
You can play with it:

main:
  x := 499
  my_lambda := ::
    print x
    x++
  my_lambda.call  // => 499
  my_lambda.call  // => 500
 (edited)

floitsch

The nice thing about lambdas is that they can use local variables, and make sure that these stay alive.
This is, why we sometimes use blocks (: print "in a block") vs lambdas (:: print "in a lambda").
Fundamentally, lambdas are more flexible, as you can return them or store them in globals, maps, ...
However, they are more expensive, which is why we prefer to use blocks in most places instead.