Haskell's flip function is defined as follows:
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
All it does is take a function and return another function that has its two parameters reversed. If you called a function f
as f a b
(f(a, b)
in Rust-like syntax), you would call flip f
as (flip f) b a
.
My unsuccessful attempt at writing this in Rust:
fn flip<A, B, C, F: Fn(A, B) -> C>(f: F) -> impl Fn(B, A) -> C {
|a, b| f(b, a)
}
Is it possible to write this in Rust?
flip() function. The flip() function is used to reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.
Flip simply takes a function and returns a function that is like our original function, only the first two arguments are flipped. We can implement it like so: flip' :: (a -> b -> c) -> (b -> a -> c)
until condition and while condition do ... statements. while stops when the condition is false, until stops when the condition is true. In the same language, two different conventions.
Both languages embrace the idea of explicitly marking things. For example, both languages encourage (in Haskell's case) or enforce (in Rust's case) marking the type signature of all functions. But that's pretty common. Haskell goes further, and requires that you mark all effectful computations with the IO type (or something similar, like MonadIO ).
Haskell is defined as a functional programming language that is general-purpose, powerful, and reliable language and hence it particularly suited for fast prototyping, proprietary business logic, enhancing the current environment of the software with properly written code and data analysis.
In the Haskell world, the overall philosophy is generally to approach "if it compiles, it works." Haskellers love enforcing almost every invariant at the type level.
This combination turns many common structures in other languages (like loops) into normal functions. But in order to make this feel natural, Haskell uses slightly odd (compared to other languages) syntax for function application.
I'm not sure what error you're getting, but I was able to implement it properly with this code (playground link for testing):
fn flip<A, B, C, F>(f: F) -> impl Fn(B, A) -> C where F: Fn(A, B) ->C {
move |a,b| f(b, a)
}
fn main() {
let sub = |a, b| a - b;
let flipped = flip(sub);
println!("Result: {}", flipped(5, 10));
}
Note the move
keyword here, which is required to force the closure returned by flip
to take ownership of f
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With