翻转功能有什么作用?

Pre*_*vin 2 purescript

我是 purescript 的新手。这是我正在学习的Leanpub-purescript一书。我无法理解翻转功能是什么。这类似于交换概念吗?

> :type flip
forall a b c. (a -> b -> c) -> b -> a -> c
Run Code Online (Sandbox Code Playgroud)

这意味着a value goes to b, then b to a, then c is itself??. 我很震惊。请解释翻转概念,如果我指的书不好,建议一些其他材料

bkl*_*ric 5

flip函数颠倒了双参数函数的参数顺序。考虑一个简单的subtract函数:

subtract :: Int -> Int -> Int
subtract a b = a - b

subtract 4 3
-- 4 - 3 = 1
Run Code Online (Sandbox Code Playgroud)

如果flipsubtract函数上调用,它会更改从以下减去的数字:

(flip subtract) 4 3
-- 3 - 4 = -1
Run Code Online (Sandbox Code Playgroud)

它还适用于不同参数类型的函数:

showIntAndString :: Int -> String -> String
showIntAndString int string = (show int) <> string

showIntAndString 4 "asdf"
-- "4asdf"

(flip showIntAndString) "asdf" 4
-- "4asdf"
Run Code Online (Sandbox Code Playgroud)

如果它对您更有意义,请尝试将 flip 视为一个函数,该函数接受一个双参数函数作为参数并返回另一个双参数函数作为结果:

flip :: forall a b c.
    (a -> b -> c) -- takes a function
    -> (b -> a -> c) -- returns a function with flipped arguments
Run Code Online (Sandbox Code Playgroud)

用例之一flip是当您想要部分应用一个函数,但您想要部分应用的参数在第二位时。然后flip,您可以使用原始函数,并部分应用生成的函数。

  • 别客气。`show` 返回其参数的字符串表示形式。很像其他语言中的 `toString()`。例如`show 123`等于`"123"`。有关 PureScript 中函数和类型的更多信息,请访问 [Pursuit](https://pursuit.purescript.org)。[这里的文档](https://pursuit.purescript.org/packages/purescript-prelude/3.1.0/docs/Data.Show#v:show) 用于`show`。 (3认同)