Ref:
I have searched a lot of links, but it seems that no one could explain it specifically. Could anyone give some code(use javaScript) to explain it?
Ref:
I have searched a lot of links, but it seems that no one could explain it specifically. Could anyone give some code(use javaScript) to explain it?
TL;DR: In short, Algebraic Effects are an exception mechanism which lets the throw
ing function continue its operation.
Try to think of Algebraic Effects as some sort of try
/ catch
mechanism, where the catch
handler does not just "handle the exception", but is able to provide some input to the function which threw the exception. The input from the catch
handler is then used in the throwing function, which continues as if there was no exception.
Let's consider a function which needs some data to perform its logic:
function throwingFunction() {
// we need some data, let's check if the data is here
if (data == null) {
data = throw "we need the data"
}
// do something with the data
}
Then we have the code that invokes this function:
function handlingFunction() {
try {
throwingFunction();
} catch ("we need the data") {
provide getData();
}
}
As you see, the throw
statement is an expression evaluating to the data provided by the catch
handler (I used the keyword provide
here, which afaik does not exist in any programming language of today).
Algebraic Effects are a very general and basic concept. This can be seen by the fact that many existing concepts can be expressed in Algebraic Effects.
try
/catch
If we had Algebraic Effects but no Exceptions in our favorite programming language, we could just omit the provide
keyword in the catch
handler, and voilà, we would have an exception mechanism.
In other words, we would not need any Exceptions if we had Algebraic Effects.
async
/await
Look again at the pseudo code above. Let's assume the data which we need has to be loaded over the network. If the data is not yet there, we would normally return a Promise and use async
/await
to handle it. This means that our function becomes an asynchronous function, which can only be called from asynchronous functions. However, Algebraic Effects are capable of that behavior too:
function handlingFunction() {
try {
throwingFunction();
} catch ("we need the data") {
fetch('data.source')
.then(data => provide data);
}
}
Who said that the provide
keyword has to be used immediately?
In other words, had we had Algebraic Effects before async
/await
, there would be no need to clutter up the languages with them. Furthermore, Algebraic Effects would not render our functions colorful - our function does not become aynchronous from the language viewpoint.
Let's say we want to have some log statements in our code, but we don't yet know which logging library it will be. We just want some general log statements (I replaced the keyword throw
with the keyword effect
here, to make it a bit more readable - note that effect
is not a keyword in any language I know):
function myFunctionDeepDownTheCallstack() {
effect "info" "myFunctionDeepDownTheCallstack begins"
// do some stuff
if (warningCondition) {
effect "warn" "myFunctionDeepDownTheCallstack has a warningCondition"
}
// do some more stuff
effect "info" "myFunctionDeepDownTheCallstack exits"
}
And then we can connect whichever log framework in a few lines:
try {
doAllTheStuff();
}
catch ("info" with message) {
log.Info(message);
}
catch ("warn" with message) {
log.Warn(message);
}
This way, the log statement and the code that actually does the logging are separated.
As you can see, the throw
keyword is not really suited in the context of the very general Algebraic Effects. More suitable keywords would be effect
(as used here) or perform
.
There are other existing language or library constructs that could be easily realized using Algebraic Effects:
yield
. A language with Algebraic Effects does not need the yield
statement.AFAIK there are not many languages with support for Algebraic Effects out of the box (please comment if you know examples that do). However, there are languages which allow the creation of algebraic effects libraries, one example being Javascript with its function*
and yield
keywords (i.e. generators). The library redux-saga uses Javascript generators to create some Algebraic Effects:
function* myRoutineWithEffects() {
// prepare data load
let data = yield put({ /* ... description of data to load */ });
// use the data
}
The put
is an instruction that tells the calling function to execute the data load call described in the argument. put
itself does not load anything, it just creates a description of what data to load. This description is passed by the yield
keyword to the calling function, which initiates the data load.
While waiting for the results, the generator routine is paused. Then, the results are passed back to the routine and can then be used there after being assigned to the data
variable. The routine then continues with the local stack plus the loaded data.
Note that in this scenario, only the calling function (or the code that has a reference to the generator) can "serve" the algebraic effect, e.g. do data loads and other things. So it is not an algebraic effect as described above, because it is not an exception mechanism that can jump up and down the call stack.
Algebraic Effects look all nice and shiny when you hear the first time about them. I do not really know why they aren't baked into all modern programming languages. However, from working with Redux Sagas, I can say that they have one crucial downside:
Algebraic Effects sometimes make debugging a nightmare.
To debug some code using Algebraic Effects, you would pause the execution by setting breakpoints, as usual. However, during such a pause, you just see the current execution stack, and it can be difficult to get the big picture, to see which code has "called" the current Algebraic Effect. Call stacks are more complex, since the code currently executing is not always at the top of the call stack - in the example above, if the top of the call stack uses the throw
or effect
keywords, then we jump several frames down the stack to the catch
handler. If this handler then calls another function, we end up with a call stack that is not anymore a simple call stack, but more like a call tree.
Perhaps it was this complexity that have made Algebraic Effects kind of an esoteric topic so far.
raise-continuable
from r7rs scheme be said to implement algebraic effects? page 54 small.r7rs.org/attachment/r7rs.pdf
Sep 26, 2021 at 17:01
raise-continuable
doesn't do much; effectively, it just calls a pre-installed handler procedure. What you need to properly support algebraic effect handlers are delimited continuations, which can be simulated with Scheme's first-class continuations. This is nothing that JavaScript supports unless one allows global program transformations).
Its hard to gain a solid theoretical understanding of algebraic effects without a basis in category theory, so I'll try to explain its usage in layman terms, possibly sacrificing some accuracy.
An computational effect is any computation that includes an alteration of its environment. For example, things like total disk capacity, network connectivity are external effects, that play a role in operations like reading/writing files or accessing a database. Anything that a function produces, besides the value it computes, is a computational effect. From the perspective of that function, even another function that accesses the same memory as that function does, can be considered an effect.
That's the theoretical definition. Practically, its useful to think of an effect as any interaction between a sub expression and a central control which handles global resources in a program. Sometimes, a local expression may need to send messages to the central control while execution, along with enough information so that once the central control is done, it can resume the suspended execution.
Why do we do this? Because sometimes large libraries have very long chains of abstractions, which can get messy. Using "algebraic effects", gives us a sort of short cut to pass things between abstractions, without going through the whole chain.
As a practical JavaScript example, let's take a UI library like ReactJS. The idea is that UI can be written as a simple projection of data.
This for instance, would be the representation of a button.
function Button(name) {
return { buttonLabel: name, textColor: 'black' };
}
'John Smith' -> { buttonLabel: 'John Smith', textColor: 'black' }
Using this format, we can create a long chain of composable abstractions. Like so
function Button(name) {
return { buttonLabel: name, textColor: 'black' };
}
function UsernameButton(user) {
return {
backgroundColor: 'blue',
childContent: [
Button(user.name)
]
}
}
function UserList(users){
return users.map(eachUser => {
button: UsernameButton(eachUser.name),
listStyle: 'ordered'
})
}
function App(appUsers) {
return {
pageTheme: redTheme,
userList: UserList(appUsers)
}
}
This example has four layers of abstraction composed together.
App -> UserList -> UsernameButton -> Button
Now, let's assume that for any of these buttons, I need to inherit the color theme of whatever machine it runs on. Say, mobile phones have red text, while laptops have blue text.
The theme data is in the first abstraction (App). It needs to be implemented in the last abstraction (Button).
The annoying way, would be to pass on the theme data, from App to Button, modifying each and every abstraction along the way.
App passes theme data to UserList UserList passes it to UserButton UserButton passes it to Button
It becomes obvious that in large libraries with hundreds of layers of abstraction, this is a huge pain.
A possible solution is to pass on the effect, through a specific effect handler and let it continue when it needs to.
function PageThemeRequest() {
return THEME_EFFECT;
}
function App(appUsers) {
const themeHandler = raise new PageThemeRequest(continuation);
return {
pageTheme: themeHandler,
userList: UserList(appUsers)
}
}
// ...Abstractions in between...
function Button(name) {
try {
return { buttonLabel: name, textColor: 'black' };
} catch PageThemeRequest -> [, continuation] {
continuation();
}
}
This type of effect handling, where one abstraction in a chain can suspend what its doing (theme implementation), send the necessary data to the central control (App, which has access to external theming), and passes along the data needed for continuation, is an extremely simplistic example of handling effects algebraically.
continuation
with the theme. This then causes Button to resume, now that it has the theme data.
Nov 23, 2021 at 18:57
Well as far as I understand the topic, algebraic effects are currently an academic/experimental concept that lets you alter certain computational elements (like function calls, print statements etc.) called "effects" by using a mechanism that resembles throw catch
The simplest example I can think of in a language like JavaScript is modifying the output message in lets say console.log
. Supposed you want to add "Debug Message: " in front of all your console.log
statements for whatever reason. This would be trouble in JavaScript. Basically you would need to call a function on every console.log
like so:
function logTransform(msg) { return "Debug Message: " + msg; }
console.log(logTransform("Hello world"));
Now if you have many console.log
statements every single one of them needs to be changed if you want to introduce the change in logging. Now the concept of algebraic effects would allow you to handle the "effect" of console.log
on the system. Think of it like console.log
throwing an exception before invocation and this exception (the effect) bubbles up and can be handled. The only difference is: If unhandled the execution will just continue like nothing happened. No what this lets you do is manipulate the behaviour of console.log
in an arbitrary scope (global or just local) without manipulating the actual call to console.log
. Could look something like this:
try
{
console.log("Hello world");
}
catch effect console.log(continuation, msg)
{
msg = "Debug message: " + msg;
continuation();
}
Note that this is not JavaScript, I'm just making the syntax up. As algebraic effects are an experimental construct they are not natively supported in any major programming language I know (there are however several experimental languages like eff https://www.eff-lang.org/learn/). I hope you get a rough understanding how my made-up code is intended to work. In the try catch block the effect that might be thrown by console.log
can be handled. Continuation is a token-like construct that is needed to control when the normal workflow should continue. It's not necessary to have such a thing but it would allow you to make manipulations before and after console.log
(for example you could add an extra log message after each console.log)
All in all algebraic effects are an interesting concept that helps with many real-world problems in coding but it can also introduce certain pitfalls if methods suddenly behave differently than expected. If you want to use algebraic effects right now in JavaScript you would have to write a framework for it yourself and you probably won't be able to apply algebraic effects to core functions such as console.log
anyway. Basically all you can do right now is explore the concept on an abstract scale and think about it or learn one of the experimental languages. I think that's also the reason why many of the introductory papers are so abstract.
You can check out algebraic-effects. It is a library that implements a lot of the concepts of algebraic effects in javascript using generator functions, including multiple continuations. It's a lot easier to understand algebraic-effects in terms of try-catch (Exception effect) and generator functions.