在Haskell中将列表元素相乘

use*_*887 3 haskell product list

我想要一个函数,它接受列表的内容的产品并复制其元素.

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

其中的产品:[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)
Run Code Online (Sandbox Code Playgroud)

另一个例子: 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]

ham*_*mar 12

对于第一部分,您可以使用标准函数scanl:

> scanl (*) 1 [2, 3, 4, 5]
[1,2,6,24,120]
Run Code Online (Sandbox Code Playgroud)

对于第二部分,zipWithreplicate得到我们大多数的存在方式:

> 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]]
Run Code Online (Sandbox Code Playgroud)

那么我们只需要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]
Run Code Online (Sandbox Code Playgroud)