开发者

How do you solve this Haskell problem?

开发者 https://www.devze.com 2022-12-29 21:17 出处:网络
I want to define a function replicate to replicate a list 开发者_如何学运维of numbers by its value using only list comprehension, for example:

I want to define a function replicate to replicate a list 开发者_如何学运维of numbers by its value using only list comprehension, for example:

replicate [5,1,3,2,8,1,2]
output: [5,5,5,5,5,1,3,3,3,2,2,8,8,8,8,8,8,8,8,1,2,2]

I know this would be easy to use the 'replicate' built in function but only list comprehension is allow, how can I do this?

THANKS!


Neat little problem. I solved it like this.

replicate list = [ a | a <- list, _ <- [1..a]]

Prelude> replicate [5,1,3,2,8,1,2]

[5,5,5,5,5,1,3,3,3,2,2,8,8,8,8,8,8,8,8,1,2,2]

It takes each value in the list, creates that many copies of itself, and then moves to the next value.


For kicks:

import Control.Monad
import Control.Monad.Instances

repList = concatMap $ join replicate
0

精彩评论

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