gpt4 book ai didi

list - 从列表中获取偶数位置的元素

转载 作者:行者123 更新时间:2023-12-04 19:51:24 24 4
gpt4 key购买 nike

问题:使用折叠,从列表中取出偶数位置的元素:

GHCi> evenOnly [1..10]
[2,4,6,8,10]
GHCi> evenOnly ['a'..'z']
"bdfhjlnprtvxz"

evenOnly :: [a] -> [a]
evenOnly = undefined

我首先决定获取一个交替的 0-es 和 1-s 的列表:[0,1,0,1..]

Prelude> let g = iterate (\x -> (x + 1) `mod` 2) 0
Prelude> take 10 $ g
[0,1,0,1,0,1,0,1,0,1]

然后将其与原始列表zip,得到一个对列表:[(x1, 0), (x2,1), (x3,0) .. (xn, ?)]:

Prelude> zip g [1,2,3,4,5]
[(0,1),(1,2),(0,3),(1,4),(0,5)]

之后,foldr具有过滤功能的对列表和一个空列表作为初始化值。

所以我认为这会起作用:

evenOnly :: [a] -> [a]
evenOnly xs = let g = iterate (\x -> (x + 1) `mod` 2) 0
in
foldr (\ (x, n) s -> if n == 1 then x : s else s) [] . (zip g xs)

但它给出了一个我不明白的错误:

foldr.hs:44:59: error:
• Couldn't match expected type ‘a0 -> t0 (a1, Integer)’
with actual type ‘[(Integer, a)]’
• Possible cause: ‘zip’ is applied to too many arguments
In the second argument of ‘(.)’, namely ‘(zip g xs)’
In the expression:
foldr (\ (x, n) s -> if n == 1 then x : s else s) [] . (zip g xs)
In the expression:
let g = iterate (\ x -> (x + 1) `mod` 2) 0
in
foldr (\ (x, n) s -> if n == 1 then x : s else s) [] . (zip g xs)
• Relevant bindings include
xs :: [a] (bound at foldr.hs:42:10)
evenOnly :: [a] -> [a] (bound at foldr.hs:42:1)

我认为我的想法是正确的,我只是在语法上做错了。

最佳答案

(.) 是函数组合,但 zip g xs 是列表而不是函数。您可以直接将结果列表作为参数应用到 foldr。请注意,您的参数 gxs 顺序错误:

evenOnly :: [a] -> [a]
evenOnly xs = let g = iterate (\x -> (x + 1) `mod` 2) 0
in
foldr (\ (x, n) s -> if n == 1 then x : s else s) [] (zip xs g)

关于list - 从列表中获取偶数位置的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57516945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com