重构 Haskell 个 lambda 函数
Refactoring Haskell lambda functions
我有一个 lambda 函数 ((:) . ((:) 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))
以包含它的两个参数?
您可以step-by-step将其转换为 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
我有一个 lambda 函数 ((:) . ((:) 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))
以包含它的两个参数?
您可以step-by-step将其转换为 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