我是 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??
. 我很震惊。请解释翻转概念,如果我指的书不好,建议一些其他材料
该flip
函数颠倒了双参数函数的参数顺序。考虑一个简单的subtract
函数:
subtract :: Int -> Int -> Int
subtract a b = a - b
subtract 4 3
-- 4 - 3 = 1
Run Code Online (Sandbox Code Playgroud)
如果flip
在subtract
函数上调用,它会更改从以下减去的数字:
(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
,您可以使用原始函数,并部分应用生成的函数。
归档时间: |
|
查看次数: |
580 次 |
最近记录: |