Haskell中flip函数的定义

Dan*_*mon 1 haskell functional-programming higher-order-functions

Currently I am trying to learn Haskell with the book 'Learn You a Haskell' and I'm trying to understand the implementations of the flip function in chapter 5. The problem is that the author states that if g x y = f y x is valid, then f y x = g x y must be also true. But how and why does this reversal affects the two function definitions?

I know how currying works and I also know that the -> operator is right-associative by default so the type declarations are in fact the same. I also understand the functions apart from each other but not how the reversal of g x y = f y x is in relation with this.

first flip function

flip' :: (a -> b -> c) -> (b -> a -> c)
flip' f = g
    where g x y = f y x
Run Code Online (Sandbox Code Playgroud)

second flip function

flip' :: (a -> b -> c) -> b -> a -> c
flip' f y x = f x y
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 7

我认为作者脑海中的论点被粗略地缩写为一点都不合理。但是这是我对推理的猜测。我们从第一个定义开始:

flip f = g where g x y = f y x
Run Code Online (Sandbox Code Playgroud)

现在我们观察到这是一个可咖喱的事情,并且我们使用所有与(->)和垃圾相关性的讨论来编写相同的东西,但带有的两个额外参数f。像这样:

flip f x y = g x y where g x y = f y x
Run Code Online (Sandbox Code Playgroud)

现在我们有了他所说的双向发展的方程式,g x y = f y x反之亦然。我们可以flip使用以下公式重写主体,如下所示:

flip f x y = f y x where g x y = f y x
Run Code Online (Sandbox Code Playgroud)

由于该定义的主体不再提及g,因此我们可以将其删除。

flip f x y = f y x
Run Code Online (Sandbox Code Playgroud)

现在我们几乎在那里。在最终定义中,作者交换了名称xy随处可见。我不知道他们为什么选择这样做,但这是您可以在方程式推理中采取的法律措施,所以在那里没有问题。这样做为我们提供了最终方程:

flip f y x = f x y
Run Code Online (Sandbox Code Playgroud)