Is silent programming possible in Rust?

Are some of the Haskell icons fuzzy programming translatable in Rust?

+3
source share
1 answer

You can try building a macro for this:

#[feature(macro_rules)];

macro_rules! compose_inner(
    ($var:ident, $f:ident) => (
        $f($var)
    );
    ($var:ident, $f:ident $($rest:ident )+) => (
        $f(compose_inner!($var, $($rest )+))
    );
)


macro_rules! compose(
    ($($f:ident )+) => (
        |x| compose_inner!(x, $($f )+)
    )
)

fn foo(x: int) -> f64 {
    (x*x) as f64
}

fn bar(y: f64) -> ~str {
    (y+2.0).to_str()
}

fn baz(z: ~str) -> ~[u8] {
    z.into_bytes()
}

fn main() {
    let f = compose!(baz bar foo);
    println!("{:?}", f(10));
}

Macros can probably be simpler, but this is what I came up with.

But this, of course, is not supported in the language itself. Rust is not a functional and concatenative language.

A very similar idiom is a method chain that is absolutely supported by Rust. The most striking example, I think, would be iterative transformations:

let v: ~[int] = ...;
let x: int = v.iter().map(|x| x + 1).filter(|x| x > 0).fold(0, |acc, x| acc + x/2);

True, it is not as flexible as an arbitrary composition of functions, but it looks much more natural and feels much more convenient.

+6
source

All Articles