DEV Community

Alain
Alain

Posted on

2 2

Answer: How to make an tail recursive function and test it in ReasonML?

let sum = n => {
let rec loop = (n, k) =>
if (n == 0) {
k(0);
} else {
([@tailcall] loop)(n - 1, x => k(x + n));
};
([@tailcall] loop)(n, x => x);
};
view raw tailcall.re hosted with ❤ by GitHub
let sum = n => {
let rec loop = (n, k) =>
if (n == 0) {
k(0);
} else {
loop(n - 1, x => k(x + n));
};
loop(n, x => x);
};
view raw unannotted.re hosted with ❤ by GitHub

How do you test if this reasonml function is tail recursive. The simple version show you the unannottated function and usingTailCall.re show its annotated in reasonml.

Call in terminal with:

ocamlc -annot -o tailCall -pp "refmt -p ml" -impl tailCall.re
Enter fullscreen mode Exit fullscreen mode

You can check where the tail calls are with:

grep call -A1 tailCall.annot 
Enter fullscreen mode Exit fullscreen mode

Source: https://stackoverflow.com/a/40401233/2336356
Sketch: https://sketch.sh/s/eBl2Z0Wvd21azKu6SFzb9j/

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs