Last active
April 15, 2020 10:20
-
-
Save turboMaCk/ac22cd3828a9cc1d20ce5f0d5c504089 to your computer and use it in GitHub Desktop.
Elm tail call optimization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
elm make src/Main.elm --output out.js --optimize |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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