First-class functions/Use numbers analogously: Difference between revisions

(→‎{{header|Rust}}: Added Rust)
Line 1,100:
 
This structure is identical to the treatment of Ruby's [[First-class functions#Ruby|first-class functions]] -- create a Proc object that returns a Proc object (a closure). These examples show that 0.5 times number ''n'' (or passed to function ''f'') times inverse of ''n'' (or passed to inverse of ''f'') returns the original number, 0.5.
 
=={{header|Rust}}==
<lang rust>#![feature(conservative_impl_trait)]
fn main() {
let (x, xi) = (2.0, 0.5);
let (y, yi) = (4.0, 0.25);
let z = x + y;
let zi = 1.0/z;
 
let numlist = [x,y,z];
let invlist = [xi,yi,zi];
 
let v: Vec<f64> = numlist.iter()
.zip(&invlist)
.map(|(x,y)| multiplier(*x,*y)(0.5))
.collect();
println!("{:?}", v);
}
 
fn multiplier(x: f64, y: f64) -> impl Fn(f64) -> f64 {
move |m| x*y*m
}</lang>
 
This is very similar to the [[First-class functions#Rust|first-class functions]] implementation save that the type inference works a little bit better here (e.g. when declaring <code>numlist</code> and <code>invlist</code>) and <code>multiplier</code>'s declaration is substantially simpler than <code>compose</code>'s. Both of these boil down to the fact that closures and regular functions are actually different types in Rust so we have to be generic over them but here we are only dealing with 64-bit floats.
 
=={{header|Scala}}==