2017-09-02 83 views
1

我是purescript的新手。這是我正在學習的書Leanpub-purescript。我不明白什麼是翻轉功能。這與交換概念相似嗎?翻轉功能是做什麼的?

> :type flip 
forall a b c. (a -> b -> c) -> b -> a -> c 

這意味着a value goes to b, then b to a, then c is itself??。我對此感到震驚。請解釋翻頁概念,如果我所指的書不好,建議其他一些材料

回答

3

flip函數顛倒了雙參數函數的參數順序。舉一個簡單的subtract功能:

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

subtract 4 3 
-- 4 - 3 = 1 

如果flip被呼籲subtract功能,它改變其數量被減去:

(flip subtract) 4 3 
-- 3 - 4 = -1 

它還具有不同參數類型的函數的工作原理:

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

showIntAndString 4 "asdf" 
-- "4asdf" 

(flip showIntAndString) "asdf" 4 
-- "4asdf" 

如果它對您更有意義,請嘗試將flip看作一個接受雙參數函數的函數作爲ar gument並返回另外兩個參數的函數的結果:

flip :: forall a b c. 
    (a -> b -> c) -- takes a function 
    -> (b -> a -> c) -- returns a function with flipped arguments 

其中一個用例flip是當你要部分地應用功能,但要部分應用參數是在第二位。然後您可以使用原始功能flip,並部分應用所產生的功能。

+0

謝謝你。似乎已清除。但是'showIntAndString int string =(show int)<> string'中的'(show int)'的含義是什麼? – Previn

+3

不客氣。 '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'。 – Houndolon