DEV Community

Discussion on: Functional Programming in Rust

Collapse
 
aminnairi profile image
Amin • Edited

Currying. A functional programming technique where we can create a function with many arguments

This is not the definition of currying in computer science.

Currying is (in maths and computer science) a programming technique that transforms a function of N parameters into a chain of functions (N functions) that each takes one parameter (a function of arity 1).

function uncurried(a, b) {
    return a + b;
}

function curried(a) {
    return function(b) {
        return a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
natserract profile image
Natserract • Edited

Whoa, yes i missconception about currying, thankyou for your comment, i will edit this ;)

Collapse
 
natserract profile image
Natserract

Finally:

#[derive(Debug)]
struct States<'a> {
    a: &'a i32,
    b: &'a i32,
}

trait Currying {
    type ReturnType: Fn(i32) -> i32;
    fn add(self) -> Self::ReturnType;
}

impl Currying for States<'static>{
    type ReturnType = Box<dyn Fn(i32) -> i32>;

    fn add(self) -> Self::ReturnType {
        Box::new(move|x| {
            x * self.a
        })
    }
}

let r_value: States = States {
    a: &100,
    b: &100
};

let r1 = r_value.add();
let r2 = r1(5);

assert_eq!(500, r2);