I cannot get this to work in F#. I am trying to write a tail recursive form of vector add and pass the previously calculated values using a. It is giving error "error FS0001: Type mismatch. Expecting a
''a'
but given a
''b list -> 'c list -> 'a list'
The types ''a' and ''b list -> 'c list -> 'a list' cannot be unified."
let rec vecadd a v1 v2 =
match (v1, v2) with
| ([], []) -> a
| (h1::t1, h2::t2) -> vecadd a::h1+h2 t1 t2
答案 0 :(得分:4)
First of all, you need to add parentheses around (a::h1+h2)
. Otherwise, the compiler thinks that you are calling vecadd
with a
as the argument
and then prepending that to a list. Your code gets parsed as (vecadd a)::h1+h2
instead.
Once you add the parentheses, there is one more issue. In your recursive call, the argument a::h1+h2
is not right - the operator ::
prepends a value to the front of a list and so it takes a value and a list of values. In your case, you are trying to use it to append a value to the end of the list.
You can fix this by using h1+h2::a
to add the new element to the front of the list and then reversing the list before returning it in the [], []
case:
let rec vecadd a v1 v2 =
match (v1, v2) with
| ([], []) -> List.rev a
| (h1::t1, h2::t2) -> vecadd (h1+h2::a) t1 t2