Y combinator: Difference between revisions
Content deleted Content added
Line 3,742: | Line 3,742: | ||
<lang M2000 Interpreter> |
<lang M2000 Interpreter> |
||
Module Ycombinator { |
Module Ycombinator { |
||
\\ y() return value. no use of closure |
|||
y=lambda (g, x)->g(g, x) |
|||
Print y(lambda (g, n as decimal)->if(n=0->1, n*g(g, n-1)), 10)=3628800 ' true |
|||
Print y(lambda (g, n)->if(n<=1->n,g(g, n-1)+g(g, n-2)), 10)=55 ' true |
|||
\\ Using closure in y, y() return function |
|||
y=lambda (g)->lambda g (x) -> g(g, x) |
|||
fact=y((lambda (g, n as decimal)-> if(n=0->1, n*g(g, n-1)))) |
|||
Print fact(6)=720, fact(24)=620448401733239439360000@ |
|||
fib=y(lambda (g, n)->if(n<=1->n, g(g, n-1)+g(g, n-2))) |
|||
Print fib(10)=55 |
|||
} |
} |
||
Ycombinator |
Ycombinator |
||
</lang> |
</lang> |
||
Line 3,759: | Line 3,759: | ||
<lang M2000 Interpreter> |
<lang M2000 Interpreter> |
||
Module Checkit { |
Module Checkit { |
||
Rem { |
|||
all lambda arguments passed by value in this example |
|||
There is no recursion in these lambdas |
|||
\\ Y combinator make argument f as closure, as a copy of f |
|||
Y combinator make argument f as closure, as a copy of f |
|||
m(m, argument) pass as first argument a copy of m |
|||
so never a function, here, call itself, only call a copy who get it as argument before the call. |
|||
⚫ | |||
⚫ | |||
=lambda f (x)->f(f,x) |
|||
⚫ | |||
} |
|||
=lambda f (x)->f(f,x) |
|||
} |
|||
if n<2 then { |
|||
⚫ | |||
=1 |
|||
if n<2 then =1 else =n*m(m, n-1) |
|||
} else { |
|||
} |
|||
=n*m(m, n-1) |
|||
⚫ | |||
} |
|||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
if n<=1 then { |
|||
⚫ | |||
=n |
|||
⚫ | |||
} else { |
|||
} |
|||
⚫ | |||
} |
|||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
Next i |
|||
} |
} |
||
Checkit |
Checkit |
||
// same but more compact |
|||
Module Checkit { |
|||
fac=lambda (f)->{=lambda f (x)->f(f,x)}(lambda (m, n)->{=if(n<2->1,n*m(m, n-1))}) |
|||
fib=lambda (f)->{=lambda f (x)->f(f,x)}(lambda (m, n)->{=if(n<=1->n,m(m, n-1)+m(m, n-2))}) |
|||
For i=1 to 10 |
|||
⚫ | |||
Next i |
|||
⚫ | |||
Checkit |
|||
Module CheckRecursion { |
Module CheckRecursion { |
||
fac=lambda (n) -> { |
|||
if n<2 then =1 else =n*Lambda(n-1) |
|||
} |
|||
=1 |
|||
fib=lambda (n) -> { |
|||
} else { |
|||
⚫ | |||
=n*Lambda(n-1) |
|||
} |
|||
} |
|||
⚫ | |||
} |
|||
⚫ | |||
if n<=1 then { |
|||
=n |
|||
} else { |
|||
⚫ | |||
} |
|||
} |
|||
For i=1 to 10 |
|||
Print fib(i), fac(i) |
|||
Next i |
|||
} |
} |
||
CheckRecursion |
CheckRecursion |