简体   繁体   English

haskell中两个列表上的两个操作

[英]two operations on two lists in haskell

I'm a bit of a Haskell newbie. 我有点像Haskell新手。 Let's say that i have two infinite lists of numbers A and B and I want to create another infinite list C which contains a sequence of x+y 's and xy 's where x <- A and y <- B , ie, C grows by 2 in every loop; 假设我有两个数字AB无限列表,我想创建另一个无限列表C ,其中包含x+yxy的序列,其中x <- Ay <- B ,即C在每个循环中增长2; what's the most clever way to do this? 最聪明的方法是什么?

制作由两个元素组成的列表的无限列表并将其连接起来。

concat [[x+y, x-y] | (x, y) <- zip listA listB]

You probably don't want the most clever way, since by definition it would be too clever for you to debug :-) 您可能不想要最聪明的方法,因为按照定义,调试起来太聪明了:-)

An obvious way would be to zip the infinite streams together, like so: 一种明显的方法是将无限流压缩在一起,如下所示:

zipWith k as bs
    where
        k a b = (a + b, a - b)

For infinite lists only it's just 对于无限列表,只是

mkList (x:xs) (y:ys) = x+y : x-y : mkList xs ys

and to support finite lists, too, you've to add the base case 并且要支持有限列表,还必须添加基本情况

mkList _ _ = []
f xs = concat . zipWith go xs where 
       go x y = map (($y).($x)) [(+),(-)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM