Created
November 26, 2012 08:06
-
-
Save tianshuo/4147123 to your computer and use it in GitHub Desktop.
Recursive Fizzbuzz with Y-combinator in javascript
This file contains 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
/* Recursive Fizzbuzz with Y-combinator in javascript... | |
* Tail-recursion and no loops | |
* By TiansHUo http://tianshuohu.diandian.com | |
* Y-combinator from: http://blog.jcoglan.com/2008/01/10/deriving-the-y-combinator/ | |
*/ | |
var Y = function(f) { | |
return (function(g) { | |
return g(g); | |
})(function(h) { | |
return function(n,k) { | |
return f(h(h))(n,k); | |
}; | |
}); | |
}; | |
var fizzbuzz=Y(function(f){ | |
return function(n,k){ | |
k=k||[]; | |
if(n>0){ | |
if(n%15==0) { | |
k.push("fizzbuzz"); | |
}else if(n%3==0){ | |
k.push("fizz"); | |
}else if(n%5==0){ | |
k.push("buzz"); | |
}else{ | |
k.push(n); | |
} | |
f(n-1,k); | |
}else{ | |
return document.write(k.reverse()); | |
} | |
}; | |
}); | |
fizzbuzz(35); | |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment