开发者

Iterating along 2 lists at the same time in haskell (without resorting to zip)

开发者 https://www.devze.com 2023-01-28 06:50 出处:网络
I have 2 lists: [[1,2],[4,5]] and [0, 3] and I\'d like to turn it into [[0,1,2],[3,4,5]] I\'ve created a function that does just that:

I have 2 lists:

[[1,2],[4,5]]

and

[0, 3]

and I'd like to turn it into

[[0,1,2],[3,4,5]]

I've created a function that does just that:

myFun xxs xs = map (\x -> (fst x):(snd x)) (zip xs xxs)

and it works. But I am still left wondering whether there might exist a better way to accomplish this 开发者_开发技巧without using the zip. Is there any?

Basically what I want to do is iterate along the 2 lists at the same time, something that I can't think of a way to do in Haskell without resorting to zip.

Thanks


Use zipWith. For example:

zipWith (:) [0,3] [[1,2],[4,5]]

Gives:

[[0,1,2],[3,4,5]]


Why is zip not an option?

Or should I say, zipWith.

zipWith (\x y -> x:y) xs xxs


You can move the zip into the type with ZipList from Control.Applicative:

myFun xxs xs = getZipList $ (:) <$> ZipList xs <*> ZipList xxs
0

精彩评论

暂无评论...
验证码 换一张
取 消