Skip to content

Commit 8f3c5e5

Browse files
authored
Effect Handler
1 parent 70dab7d commit 8f3c5e5

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

_posts/2024-11-05-Raft.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,3 +414,52 @@ I have shown only that part of the code below.
414414

415415
This code facilitates a mechanism that allows use to _pause_ the timer when we don't need it and start
416416
it again.
417+
418+
# Using effect handlers
419+
420+
This is from the documentation.
421+
422+
**Effect handlers are a mechanism for modular programming with user-defined effects. Effect handlers allow the programmers to describe
423+
computations that perform effectful operations, whose meaning is described by handlers that enclose the computations**
424+
425+
And I use _Early_return_ as my effect to return from my function.
426+
427+
{% highlight ocaml %}
428+
429+
type _ Effect.t += Early_return : int -> int Effect.t
430+
431+
let rec effective_request_vote
432+
(mutex : Eio.Mutex.t)
433+
(id : int)
434+
(term : int)
435+
(votes_received : int) : int Lwt.t =
436+
437+
match_with (fun () -> requestvote mutex id term votes_received)
438+
()
439+
{ effc = (fun (type c) (eff1: c Effect.t) ->
440+
match eff1 with
441+
| Early_return v -> Some (fun (k: (c,_) continuation) ->
442+
Printf.printf "Early Return" ;
443+
continue k v
444+
)
445+
| _ -> None
446+
);
447+
exnc = (function
448+
| e -> raise e
449+
);
450+
retc = (fun _ -> Lwt.return votes_received)
451+
452+
}
453+
{% endhighlight %}
454+
455+
456+
But there is a complex interplay between the effect, _LWT_ and _EIO_ as the older LWT _capnp-rpc-lwt_ is used. Eio can integrate with it.
457+
This is done because the code started using Lwt-Eio integration. The newer _capnp-rpc_ based entirely on Eio will be used later.
458+
459+
This necessitates the line in the calling functiion which produces the effect.
460+
461+
{% highlight ocaml %}
462+
Lwt.return (perform (Early_return votes_received));
463+
{% endhighlight %}
464+
465+
At this stage the code compiles but has to be tested more.

0 commit comments

Comments
 (0)