我想要一个函数,它获取两个Int列表并生成一个列表列表,其中每个列表是整个第二个列表中第一个列表的每个元素的乘积的结果。这是一个例子:
multiplyElements :: [Int] -> [Int] -> [[Int]]
[1, 2, 3]
和列表2:[4, 5, 6]
[[4, 5, 6], [8, 10, 12], [12, 15, 18]]
`
答案 0 :(得分:1)
这是一个可能的解决方案:
module ListsProduct where
-- function which given a number and a list returns a list representing
-- the elements of the list multipled by the number
g :: Int -> [Int] -> [Int]
g _ [] = []
g a (x:xs) = a*x : g a xs
-- Recursion proceeds by analysing each element of the first list
-- and multiply it by all elements of the second
f :: [Int] -> [Int] -> [[Int]]
f [] _ = [[]]
f (x:xs) b = g x b : f xs b
答案 1 :(得分:1)
感谢支持人员,这是我的决议:
multiplyByValue :: Int -> [Int] -> [Int]
multiplyByValue n list = [x*n | x <- list]
multiplyLists :: [Int] -> [Int] -> [[Int]]
multiplyLists list1 list2 = [multiplyByValue x list2 | x <- list1]