Skip to content

Make function composition stack safe #150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
},
"devDependencies": {
"eslint": "^3.17.1",
"purescript-psa": "^0.5.0-rc.1",
"pulp": "^10.0.4",
"purescript-psa": "^0.5.1",
"pulp": "^11.0.0",
"rimraf": "^2.6.1"
}
}
31 changes: 31 additions & 0 deletions src/Control/Semigroupoid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use strict";

// https://medium.com/@safareli/stack-safe-function-composition-85d61feee37e
var runComposition = function(composition, x) {
var root = composition;
var val = x;
var stack = [];
for (;;) {
if (root._0 !== undefined){
stack.push(root._1);
root = root._0;
} else {
val = root(val);
if (stack.length === 0) {
return val;
}
root = stack.shift();
}
}
};

exports.functionCompose = function(f) {
return function(g) {
var res = function composition(x) {
return runComposition(composition, x);
};
res._0 = g;
res._1 = f;
return res;
};
};
4 changes: 3 additions & 1 deletion src/Control/Semigroupoid.purs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ class Semigroupoid a where
compose :: forall b c d. a c d -> a b c -> a b d

instance semigroupoidFn :: Semigroupoid (->) where
compose f g x = f (g x)
compose = functionCompose

foreign import functionCompose :: forall b c d. (c -> d) -> (b -> c) -> (b -> d)

infixr 9 compose as <<<

Expand Down
10 changes: 10 additions & 0 deletions test/Test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,21 @@ type AlmostEff = Unit -> Unit

main :: AlmostEff
main = do
functionComposition
testNumberShow show
testOrderings
testOrdUtils
testIntDegree

functionComposition :: AlmostEff
functionComposition =
assert
("composition is stack safe")
(composeGo (_ + 1) id 0 0 == 100000)

composeGo :: forall x a. Semigroupoid x => x a a -> x a a -> Int -> x a a
composeGo f acc n = if n == 100000 then acc else composeGo f (compose acc f) (n + 1)

foreign import testNumberShow :: (Number -> String) -> AlmostEff
foreign import throwErr :: String -> AlmostEff

Expand Down