使用嵌套列表列出乘法

时间:2015-11-04 08:52:29

标签: list haskell recursion functional-programming

考虑列表清单

thisList = [[1], [1, 1], [1, 1, 1]]

我怎么能多次thisList以便它会产生另一个列表

anotherList = [[1], [2, 2], [3, 3, 3]]

我已经完成了这个功能

reps = [1] : map (\ns -> head ns:ns) reps

产生thisList

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

你可以这样做:

zipWith (\x -> map (const x)) [1..] thisList

使用示例:

Prelude> let thisList = [[1], [1,1], [1,1,1]]
Prelude> zipWith (\x -> map (const x)) [1..] thisList
[[1],[2,2],[3,3,3]]

或更简单:

zipWith (map . const) [1..] thisList

这很容易。 zipWith f as bs相当于map (uncurry f) $ zip as bs。所以我们有:

zip [1..] thisList == [(1, [1]), (2, [1,1,]), (3, [1,1,1])]

然后我们将f应用于每对,所以:

map (const 1) [1]   == [const 1 1] == [1]
map (const 2) [1,1] == [const 2 1, const 2 1] == [2,2]
map (const 3) [1,1,1] == [const 3 1, const 3 1, const 3 1] == [3,3,3]

如果您的意思是长度为n的子列表应替换为长度为[n, n, ..., n]的{​​{1}},如:

n

然后你必须改变方法:

thisList = [[1, 1], [1], [1], [1, 1, 1]]
result = [[2,2], [1], [1], [3,3,3]]

示例:

map (\xs -> let len = length xs in replicate len len) thisList