3

我想要一个函数,它采用列表初始值的乘积并复制其元素。

例如列表是:[2, 3, 4, 5]

其 inits 的乘积:[1, 2, 6, 24, 120]

最后,列表应如下所示:[1, 1, 2, 2, 2, 6, 6, 6, 6, 24, 24, 24, 24, 24].

我的问题是不[1, 2, 6, 24, 120]应该改变,但我无法解决它,我对haskell很陌生。您不需要修改此代码,您可以新建一个。

makeSystem :: Integral a => [a] -> [a]
makeSystem l= replicate (l !! 0) ((map product(inits l))!!0) ++ asd (tail l) where
 inits [] = [[]]
 inits (x:xs) = [[]] ++ map (x:) (inits xs)

另一个例子:makeSystem [5,2,5,2,5,2]

结果:[1, 1, 1, 1, 1, 5, 5, 10, 10, 10, 10, 10, 50, 50, 100, 100, 100, 100, 100, 500, 500]

4

1 回答 1

12

对于第一部分,您可以使用标准功能scanl

> scanl (*) 1 [2, 3, 4, 5]
[1,2,6,24,120]

对于第二部分,zipWithwithreplicate让我们大部分时间到达那里:

> zipWith replicate [2, 3, 4, 5] [1, 2, 6, 24, 120]
[[1,1],[2,2,2],[6,6,6,6],[24,24,24,24,24]]

那么我们只需要concat这些列表。

把它们放在一起:

> let makeSystem xs = concat $ zipWith replicate xs (scanl (*) 1 xs)
> makeSystem [2, 3, 4, 5]
[1,1,2,2,2,6,6,6,6,24,24,24,24,24]
> makeSystem [5, 2, 5, 2, 5, 2]
[1,1,1,1,1,5,5,10,10,10,10,10,50,50,100,100,100,100,100,500,500]
于 2013-05-11T23:30:29.720 回答