/ / Como posso multiplicar duas listas por elementos no Haskell? - lista, haskell

Como posso multiplicar duas listas por elementos no Haskell? - lista, haskell

Eu quero uma função que obtenha duas listas de Int e gere uma lista de listas, onde cada lista é o resultado do produto de cada elemento da primeira lista pela segunda lista inteira. Aqui está um exemplo:

  • Definição da função: multiplyElements :: [Int] -> [Int] -> [[Int]]
  • O que eu quero fazer:
  • Lista 1: [1, 2, 3] e lista 2: [4, 5, 6]
  • Resultado: [[4, 5, 6], [8, 10, 12], [12, 15, 18]]

`

Respostas:

1 para resposta № 1

Aqui está uma solução possível:

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 para resposta № 2

Obrigado pelo apoio pessoal, aqui está a minha resolução:

multiplyByValue :: Int -> [Int] -> [Int]
multiplyByValue n list = [x*n | x <- list]

multiplyLists :: [Int] -> [Int] -> [[Int]]
multiplyLists list1 list2 = [multiplyByValue x list2 | x <- list1]