Skip to content

Instantly share code, notes, and snippets.

@turboMaCk
Last active April 15, 2020 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turboMaCk/ac22cd3828a9cc1d20ce5f0d5c504089 to your computer and use it in GitHub Desktop.
Save turboMaCk/ac22cd3828a9cc1d20ce5f0d5c504089 to your computer and use it in GitHub Desktop.
Elm tail call optimization
#!/usr/bin/env bash
elm make src/Main.elm --output out.js --optimize
module Main exposing (main)
import Html
sumFromZero : Int -> Int
sumFromZero n =
sumFromZeroTail 0 n
sumFromZeroTail : Int -> Int -> Int
sumFromZeroTail acc n =
if n - 0 == 0 -- make sure the equality check is not using structural polymorphic version
then acc
else sumFromZeroTail (acc + n) (n - 1)
-- Make sure function is not "treeshaked" away
main = Html.text <| String.fromInt <| sumFromZero 100
var $author$project$Main$sumFromZero = function (n) {
// curing optimization
return A2($author$project$Main$sumFromZeroTail, 0, n);
// currying optimization
var $author$project$Main$sumFromZeroTail = F2(
function (acc, n) {
sumFromZeroTail:
while (true) { // tailcall compiled to loop
if (!(n - 0)) { // non polymorphic structural equality check
return acc;
} else {
var $temp$acc = acc + n,
$temp$n = n - 1;
acc = $temp$acc;
n = $temp$n;
continue sumFromZeroTail;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment