[英]Haskell Creating list of numbers
Hi Im new to Haskell and wish to write a simple code. 嗨,我是Haskell的新手,希望写一个简单的代码。 I want to write a function which creates a list of numbers. 我想写一个创建数字列表的函数。 Where it starts of with 1 and increase with 2n+1 and 3n+1 so for example output should be like take 6 myList = [1,3,4,7,9,10] 从1开始,用2n + 1和3n + 1增加所以例如输出应该像6 myList = [1,3,4,7,9,10]
I think i need to use recursion but not sure how to do it in list format. 我想我需要使用递归但不知道如何以列表格式进行。
Any help will be appreciated. 任何帮助将不胜感激。 Thanks 谢谢
Actually, I am not sure if I get your idea. 实际上,我不确定我是否明白了。 But Is this what you want? 但这是你想要的吗?
generator list = list ++ generator next
where
next = (map (\n -> 2 * n + 1) list) ++ (map (\n -> 3 * n + 1) list)
Oh, you can use generator [1] to fire up. 哦,你可以使用发电机[1]启动。 like this: 像这样:
take 100 $ generator [1]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) | x == y = x : merge xs ys
| x < y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
print $ take 10 $ merge [1,3..] [1,4..]
--[1,3,4,5,7,9,10,11,13,15]
As luqui said, we could use info such as do duplicates matter and does order matter. 正如luqui所说,我们可以使用诸如重复事项之类的信息并确实有序。 If the answers are no and no then a simple concatMap works fine: 如果答案是否定,那么简单的concatMap工作正常:
myList = 1 : concatMap (\n -> 2*n+1 : 3*n+1 : []) myList
Results in: 结果是:
> take 20 myList
[1,3,4,7,10,9,13,15,22,21,31,19,28,27,40,31,46,45,67,43]
If the answers are yes and yes then I imagine it could be cleaner, but this is sufficient: 如果答案是肯定的,那么我认为它可能更清洁,但这就足够了:
myList = abs
where
abs = merge as bs
as = 1 : map (\n -> 2*n+1) abs
bs = 1 : map (\n -> 3*n+1) abs
merge (x:xs) (y:ys)
| x == y = x : merge xs ys
| x < y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
Results in: 结果是:
> take 20 myList
[1,3,4,7,9,10,13,15,19,21,22,27,28,31,39,40,43,45,46,55]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.