Your code honestly has more wrong with it than right: ;-]
- It's not tail-recursive
- Use of
function
whenxs
andys
are separate parameters - Incomplete pattern match
- Having one branch evaluate to a list and another evaluate to a scalar
- All products are manually added together except for the last, which has a
List.reduce
run over a single-element list – slightly backwards ;-]
Here's a sensible implementation that fixes all of the above:
let inline multvec xs ys = List.map2 (*) xs ys |> List.sum
Note that if performance is a primary concern then it may be worth avoiding List.sum
, as it uses checked arithmetic. One could do the following instead if using unchecked arithmetic is okay:
let inline multvec xs ys = List.map2 (*) xs ys |> List.reduce (+)
If you really want to do this manually, here's one approach:
let inline multvec xs ys =
let rec impl acc = function
| [], [] -> acc
| x::xs', y::ys' -> impl (x * y + acc) (xs', ys')
| _ -> failwith "lists must be of equal length"
impl LanguagePrimitives.GenericZero (xs, ys)