Skip to content

Instantly share code, notes, and snippets.

@keyvanakbary
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save keyvanakbary/1bd2c0bcba93e1dcc318 to your computer and use it in GitHub Desktop.

Select an option

Save keyvanakbary/1bd2c0bcba93e1dcc318 to your computer and use it in GitHub Desktop.
Continuation-passing style
#Direct style
factorial = (n) ->
return 1 if n is 0
n * factorial(n-1)
console.log factorial(3)
#6
#Continuation-passing style
eq_ = (n1, n2, fn) ->
fn(n1 is n2)
sub_ = (n1, n2, fn) ->
fn(n1 - n2)
mul_ = (n1, n2, fn) ->
fn(n1 * n2)
factorial_ = (n, fn) ->
eq_ n, 0, (isEqual) ->
return fn(1) if isEqual
sub_ n, 1, (nm1) ->
factorial_ nm1, (facNm1) ->
mul_(n, facNm1, fn)
factorial_ 3, (result) ->
console.log result
#6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment