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其中g与f完全相同的计算
==
let transform1 (f:a->b->c) : (b->a->c) =
?
3 个解决方案
#1
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 callf
, - and a
b
, - and an
a
, - and then "uses"
f
with thea
and theb
in order to produce ac
.
函数a - > b - > c我们称之为f,
和一个b,
和一个,
然后用a和b“使用”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:
由于只有一种方法可以“使用”f与a和b产生一个c,你可以这样写下来:
flip f b a = f a b
and that's it.
就是这样。
#2
You can define a swap
function thus:
您可以定义交换功能:
let swap f a b = f b a
#3
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 = (\b a -> f a b) in ...
所以在一个let语句中:让g =(\ b a - > f a b)in ...
#1
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 callf
, - and a
b
, - and an
a
, - and then "uses"
f
with thea
and theb
in order to produce ac
.
函数a - > b - > c我们称之为f,
和一个b,
和一个,
然后用a和b“使用”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:
由于只有一种方法可以“使用”f与a和b产生一个c,你可以这样写下来:
flip f b a = f a b
and that's it.
就是这样。
#2
You can define a swap
function thus:
您可以定义交换功能:
let swap f a b = f b a
#3
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 = (\b a -> f a b) in ...
所以在一个let语句中:让g =(\ b a - > f a b)in ...