Last active
December 25, 2018 16:07
-
-
Save KSXGitHub/b4e58211720c1694e59839b367630c9d to your computer and use it in GitHub Desktop.
Compose function in Rust
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
use core::ops::{Add, Mul}; | |
use core::marker::Copy; | |
use std::fmt::Display; | |
fn compose<X, Y, Z> ( | |
f: impl Fn(X) -> Y, | |
g: impl Fn(Y) -> Z | |
) -> impl Fn(X) -> Z { | |
move |x: X| g(f(x)) | |
} | |
fn logfn<X: Display + Copy, Y: Display + Copy> ( | |
name: impl Display, | |
func: impl Fn(X) -> Y | |
) -> impl Fn(X) -> Y { | |
move |x: X| { | |
let y = func(x); | |
println!("> {} ({}) = {}", name, x, y); | |
y | |
} | |
} | |
fn double<X: Add + Copy> (x: X) -> X::Output { | |
x + x | |
} | |
fn square<X: Mul + Copy> (x: X) -> X::Output { | |
x * x | |
} | |
fn main () { | |
let double_then_square = logfn("double_then_square", compose( | |
logfn("double", double), | |
logfn("square", square) | |
)); | |
println!("Result {}", double_then_square(3)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment