Last active
September 9, 2023 12:12
-
-
Save mfirhas/d2f9711415edea471c0a4f42f1f46f79 to your computer and use it in GitHub Desktop.
Print your name with y combinator
This file contains hidden or 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
| // to run: rustc -C opt-level=3 main.rs && ./main | |
| trait YF<T, U> { | |
| fn apply(&self, yf: &dyn YF<T, U>, u: T) -> U; | |
| } | |
| impl<T, U, F> YF<T, U> for F | |
| where | |
| F: Fn(&dyn YF<T, U>, T) -> U, | |
| { | |
| fn apply(&self, yf: &dyn YF<T, U>, t: T) -> U { | |
| self(yf, t) | |
| } | |
| } | |
| fn y<T, U>(f: impl Fn(&dyn Fn(T) -> U, T) -> U) -> impl Fn(T) -> U { | |
| move |n| { | |
| (&|yf: &dyn YF<T, U>, x| yf.apply(yf, x))( | |
| &|yf: &dyn YF<T, U>, x| f(&|z| yf.apply(yf, z), x), | |
| n, | |
| ) | |
| } | |
| } | |
| fn print_name(name: &str, n: i32) { | |
| let print = |f: &dyn Fn(i32) -> (), t| { | |
| if t > 0 { | |
| println!("{name}"); | |
| f(t - 1) | |
| } | |
| }; | |
| y(print)(n) | |
| } | |
| fn main() { | |
| let name = "fathir"; | |
| let n = 100; | |
| print_name(name, n); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment