[英]Refactoring Haskell lambda functions
我有一個 lambda function ((:). ((:) x))
像這樣傳遞給foldr
: foldr ((:). ((:) x)) [] xs
其中xs
是一個二維列表。 我想重構以使其更清晰(這樣我可以更好地理解它)。 我想它會像這樣完成:
foldr (\ element acc -> (element:acc) . (x:acc)) [] xs
但這給了我錯誤:
ex.hs:20:84: error:
• Couldn't match expected type ‘a0 -> b0’ with actual type ‘[[a]]’
• Possible cause: ‘(:)’ is applied to too many arguments
In the second argument of ‘(.)’, namely ‘(x : acc)’
In the expression: (element : acc) . (x : acc)
In the first argument of ‘foldr’, namely
‘(\ element acc -> (element : acc) . (x : acc))’
• Relevant bindings include
acc :: [[a]] (bound at ex.hs:20:60)
element :: [a] (bound at ex.hs:20:52)
xs :: [[a]] (bound at ex.hs:20:30)
x :: [a] (bound at ex.hs:20:28)
prefixes :: [a] -> [[a]] (bound at ex.hs:20:1)
|
20 | prefixes = foldr (\x xs -> [x] : (foldr (\ element acc -> (element:acc) . (x:acc)) [] xs)) []
|
編輯:我圍繞這個片段的所有相關代碼是
prefixes :: Num a => [a] -> [[a]]
prefixes = foldr (\x acc -> [x] : (foldr ((:) . ((:) x)) [] acc)) []
它的調用是:
prefixes [1, 2, 3]
我如何重構 lambda ((:). ((:) x))
以包含其 arguments?
您可以逐步將其轉換為 lambda。
(:) . ((:) x)
\y -> ((:) . (((:) x)) y -- conversion to lambda
\y -> (:) (((:) x) y) -- definition of (.)
\y -> (:) (x : y) -- rewrite second (:) using infix notation
\y z -> (:) (x : y) z -- add another parameter
\y z -> (x : y) : z -- rewrite first (:) using infix notation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.