3 ms·
thats the thing though, elixir you can write it in a synchronous style and to make it concurrent is usually very easy because the semantics of regular and concu
by weatherlight 3y ago
thats the thing though, elixir you can write it in a synchronous style and to make it concurrent is usually very easy because the semantics of regular and concurrent code is essentially the same.
for example refactoring something like this:
File.stream!("path/to/some/file")
|> Stream.flat_map(&String.split(&1, " "))
|> Enum.reduce(%{}, fn word, acc ->
Map.update(acc, word, 1, & &1 + 1)
end)
|> Enum.to_list()
to be async, concurrent, (Flow uses GenServers under the hood, A GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously and so on.)
File.stream!("path/to/some/file")
|> Flow.from_enumerable()
|> Flow.flat_map(&String.split(&1, " "))
|> Flow.partition()
|> Flow.reduce(fn -> %{} end, fn word, acc ->
Map.update(acc, word, 1, & &1 + 1)
end)
|> Enum.to_list()
The point is the code isn't radically different and is easy to understand if you understand the first block of code.
- chefandy 3y agoYeah— as a primarily python guy, I find concurrency much more palatable in elixir than in js. As a relatively infrequent js user, I have tripped on its asynchronicity for decades. After learning in Perl, shell scripting, and a smidge off C in the early 2ks, then PHP and python in the subsequent decade, I rage quit js every time I picked it up for anything significant until like 10 years ago. For the first few years, I always forgot basic facets of the language like the scope of "this" in anonymous callback functions. While it's not a close analog, the way Unreal Engine's node-based "no code" Blueprints language approaches asynchronicity just feels so much more natural. Even hopeful pre-hello-world coders seem to conceptually get "well I can't get that because this hasn't happened yet." Having graphical representations of things both in nodes and in-game obviously helps in ways that wouldn't make sense in js, but being built from the ground up to handle it does show that it can be approached more intuitively.
- _v7gu 3y agoNode's "experimental" stream api also leads to code with similar semantics. It gives some additional concurrency options, but of course no parallelism outside of waits. createReadStream("file.txt") .flatMap((chunk) => chunk.split(" ")) .reduce((acc, word) => { acc[word] = (acc[word] ?? 0) + 1; return acc; }, {})