简体   繁体   中英

How can I swap the order of application in a defined F# function?

Given a general function f:a->b->c

I want to create the function that does the same thing/computation that f does but with the order of the two input parameters (or the currying order) swapped around.

So looking for g:b->a->c where g does the exact same computation as f

==

let transform1 (f:a->b->c) : (b->a->c) = 
?

您可以定义swap功能:

let swap f a b = f b a 

You can actually tell from the type of the function how to do this.

transform1 has the type (a -> b -> c) -> (b -> a -> c) or, equivalently, (a -> b -> c) -> b -> a -> c .

So what you're looking for is a function that takes

  • a function a -> b -> c which we'll call f ,
  • and a b ,
  • and an a ,
  • and then "uses" f with the a and the b in order to produce a c .

Since there's only one way to "use" f with the a and the b that produces a c you write that way down:

flip f b a = f a b

and that's it.

In Haskell you'd do that like this:

g b a = f a b -- or using lambda expressions: (\b a -> f a b) 

So in a let statement: let g = (\\ba -> fab) in ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM