'Repeat' in Haskell?

白昼怎懂夜的黑 提交于 2021-02-16 15:49:45

问题


I'm very new to Haskell, and I have a simple question.

What function can I use with a and b that will result in a, b times.

Example:
a = 4 | b = 3
Would return:
[4, 4, 4]

Thanks!


回答1:


replicate:

replicate 3 4

will be:

[4,4,4]

When you know what's the type of the function you need (in this case it was quite obvious that the function you needed had a type similar to Int -> a -> [a]) you can use Hoogle in order to find it.




回答2:


You could also use recursion (although the solutions above should be preferred of course):

rep a 0 = []
rep a b = a : rep a (b-1)



回答3:


Of course peoro is right, you should use replicate.

However, a very common pattern for such tasks is to construct an infinite list, and take as much as you need from it (either using take or takeWhile):

rep a b = take b $ repeat a

Another (more educational than practical) approach is to use a list of the right length, and map all elements to a:

rep a b = map (const a) [1..b]

An very inefficient, but interesting version is

rep a b = until ((b==).length) (a:) []



回答4:


.. or simply something like that

> take 3 [4,4..]
> [4,4,4]


来源:https://stackoverflow.com/questions/5592624/repeat-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!