所以我试图将一个列表的第 n 个元素与另一个列表的第 n 个元素相乘,然后将它们加在一起
let listMulti xList yList =
|> [for x in xList do
for y in yList do
yield x*y ] // multiplies all the elements on x with y
|> List.filter(fun x-> List.nth % List.length (xList) =1 ) //gets the elements 1 , 4, 7 for a list of size 3. This is scalable
|> List.sum //add them all up
所以这里的想法是
>listMulti [1;2;3][4;5;6];;
val it : int = 32
所以 1*4 + 2 *5 + 3*6 = 32 ,但我却得到了
错误 FS0010:绑定(bind)中出现意外的中缀运算符
帮忙?
最佳答案
该错误是因为您以奇怪的方式使用List.nth
。
我会做类似的事情
List.zip xlist ylist
|> List.sumBy (fun (a,b) -> a*b)
这里 list.zip
组合了列表 - 所以如果您有 [1;2;3]
和 [4;5;6]
你得到[(1,4);(2,5);(3,6)]
。然后你只需一次乘法和求和即可。
关于f# - 如何在 F# 中将列表的两个第 n 个元素相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33233484/