Scala function with a recursive function parameter -


i curious if can implement scala function similar javascript function. obviously, can inner function.

knowing scala has declare parameter type , arity upfront, wonder if there use implement js function. thanks.

function factorial(x) {   if (x < 0) throw error("cannot calculate factorial of negative number");   return (function(f) {     return f(f, x, 1);   })(function(f, i, fact) {     return === 0 ? fact : f(f, i-1, i*fact);   }); } 

if have understood question correctly, indeed can , best known approach use what's called y-combinator. in short y-combinator takes function parameter , keeps applying it. y-combinator has no knowledge of parameter types involved

copying example y-combinator right rosetta code:

def y[a,b](f: (a=>b)=>(a=>b)) = {   case class w(wf: w=>a=>b) {     def apply(w: w) = wf(w)   }   val g: w=>a=>b = w => f(w(w))(_)   g(w(g)) } 

defines combinator. can pass recursive function

val fac = y[int, int](f => => if (i <= 0) 1 else f(i - 1) * i) fac: int => int = <function1> 

and give evaluate

scala> fac(6) res0: int = 720 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -