简体   繁体   English

如何在定义的F#函数中交换应用程序的顺序?

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

Given a general function f:a->b->c 给定一般函数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. 我想创建一个函数,它执行与f相同的事情/计算,但是交换了两个输入参数(或currying命令)的顺序。

So looking for g:b->a->c where g does the exact same computation as f 所以寻找g:b->a->c其中gf完全相同的计算

== ==

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 . transform1具有类型(a -> b -> c) -> (b -> a -> c)或等效地, (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 , 函数a -> b -> c我们称之为f
  • and a b , 和一个b
  • and an a , a
  • and then "uses" f with the a and the b in order to produce a c . 然后用ab “使用” f以产生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: 由于只有一种方法可以“使用” fab产生一个c你可以这样写下来:

flip f b a = f a b

and that's it. 就是这样。

In Haskell you'd do that like this: 在Haskell你会这样做:

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 ... 所以在一个let语句中: let g = (\\ba -> fab) in ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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