[英]How does Haskell evaluate this function defined with partial application?
我試圖了解Haskell如何評估pp1 [1,2,3,4]
以獲得[(1,2),(2,3),(3,4)]
:
1. xnull f [] = []
2. xnull f xs = f xs
3. (/:/) f g x = (f x) (g x)
4. pp1 = zip /:/ xnull tail
我開始是這樣的:
a) pp1 [1,2,3,4] = (zip /:/ xnull tail) [1,2,3,4] -- (rule 4).
b) (zip /:/ xnull tail) [1,2,3,4]
= (zip (xnull [1,2,3,4]) (tail) [1,2,3,4]) -- (rule 3)
c) -- I'm not sure how to continue because xnull receives a function
-- and a param, and in this case it only receives a param.
有什么幫助嗎?
這是錯的
b) (zip /:/ xnull tail) [1,2,3,4] = (zip (xnull [1,2,3,4]) (tail) [1,2,3,4]) (rule 3)
因為應該
b) (zip /:/ xnull tail) [1,2,3,4] = (zip [1,2,3,4] (xnull tail [1,2,3,4])) (rule 3)
錯誤在於讀取zip /:/ xnull tail
就像(zip /:/ xnull) tail
而不是zip /:/ (xnull tail)
。
只是繼續擴展:
pp1 [1, 2, 3, 4] = zip /:/ xnull tail $ [1, 2, 3, 4]
-- inline (/:/) f g x = f x (g x)
-- f = zip, g = xnull tail, x = [1, 2, 3, 4]
-- therefore:
= zip [1, 2, 3, 4] (xnull tail $ [1, 2, 3, 4])
-- inline the definition of xnull and note that the argument is not null
-- so we just want f x, or tail [1, 2, 3, 4]
= zip [1, 2, 3, 4] (tail [1, 2, 3, 4])
-- evaluate tail
= zip [1, 2, 3, 4] [2, 3, 4]
-- evaluate zip
= [(1, 2), (2, 3), (3, 4)]
操作員的出席很重要。 您沒有指定(/:/)
的關聯性,因此默認情況下它相對較弱。 因此, (xnull tail)
綁定比(/:/)
緊。
另外,作為補充說明, (/:/)
在Control.Applicative
已作為(<*>)
存在於標准庫中。 它足夠通用,因此可能很難看清,但是Reader
的Applicative
實例(或者可能更好地理解為Applicative
函數)提供了此確切實例。 從Control.Monad
也稱為ap
。
zip <*> tail :: [b] -> [(b, b)]
zip <*> tail $ [1, 2, 3, 4] = [(1, 2), (2, 3), (3, 4)]
我知道這有點老了。 但是無論如何,這是我的看法。
有助於查看定義
pp1 = zip /:/ xnull tail
= (zip) /:/ (xnull tail)
= (/:/) zip (xnull tail)
請注意,括號(xnull tail)
周圍的括號表示函數應用程序具有較高優先級的中綴運算符。
現在(/:/)
的定義是返回另一個函數q
,該函數將采用參數x
並返回通過部分應用其第一個參數r
到應用第二個參數s
返回的結果來應用該函數的結果。
也就是說, f
需要至少能夠接受2個參數,而g
僅需要至少接受1個參數。
(/:/) f g = q
where
q x = r s
where
r = f x
s = g x
注意r
是fx
,所以qx
是fxs
。
寫起來會更清楚
f /:/ g = (\x -> f x (g x))
現在給出
pp1 = zip /:/ xnull tail
我們可以擴展到
pp1 = q
where
q x = r s
where
r = zip x
s = xnull tail x
要么
pp1 = (\x -> zip x $ xnull tail x)
剩下的只是用[1,2,3,4]
替換x
並進行評估。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.