2列表haskell的产品

时间:2017-05-11 09:45:41

标签: haskell

我有2个列表,x和y,我必须计算产品 来自x
(xi^2 - yi^2 + 2*xi*yi) xi 和来自

yi
 List x = [2,4,5,6,8] xi = 2/3/...
 List y = [7,3,4,59,0] yi = 7/3/4...

这有点棘手,因为我只能使用没有 product函数的函数而没有递归和列表理解。

prod :: [Int] -> [Int] -> Int

我会自己编写产品功能:

product :: [Integer] -> Integer
product []     = 1
product i f = foldl (*) 1 [i..f]

但我不知道如何将它应用于两个字符串。

2 个答案:

答案 0 :(得分:1)

请允许我重复使用@WillemVanOnsem的优秀答案:

首先,你必须以某种方式加入这两个名单。 zip :: [a] - > [b] - > [(a,b)]是一个方便的功能,从两个列表中返回一个对列表。

zip [2,4,5,6,8] [7,3,4,59,0] 
> [(2,7),(4,3),(5,4),(6,59),(8,0)]

现在,你必须完成你的工作。让我们定义你必须应用于一对的函数:

squareB :: (Integer,Integer) -> Integer
squareB (x,y)  = x^2 - y^2 + 2*x*y

让我们使用map将二项式函数的平方应用到每一对:

multiplicands:: [Integer] -> [Integer] -> [Integer] 
multiplicands xs1 xs2 = map squareB (zip xs1 xs2)

例如:

multiplicands  [2,4,5,6,8] [7,3,4,59,0]
>[-17,31,49,-2737,64]

现在,让我们使用基本案例1的(*)从左侧折叠它们,即:(((1 * x1)* x2).... xn):

solution :: [Integer] -> [Integer] -> Integer
solution xs1 xs2 = foldl (*) 1  (multiplicands xs1 xs2)

让我们检查一下这个功能:

solution [2,4,5,6,8] [7,3,4,59,0]
> 452336326

威廉姆斯的功能:

twoListProduct [2,4,5,6,8] [7,3,4,59,0]
> 4523363264

答案 1 :(得分:0)

你也可以这样做;

quadratics :: Num a => Int -> [a] -> [a] -> a
quadratics i ns ms = ((\(f,s) -> f*f + 2*f*s - s*s) . head . drop i . zip ns) ms

*Main> quadratics 0 [2,4,5,6,8] [7,3,4,59,0]
-17
*Main> quadratics 3 [2,4,5,6,8] [7,3,4,59,0]
-2737
相关问题