Sova
Sova

Reputation: 61

How to recursively get scalar value from 2 lists?

The task is to get scalar value from 2 lists recursively. I wrote the code that I think should work, but I am having some type related problem

let rec scalar2 (a, b) = function
  | ([], []) -> 0
  | ([x : int], [y : int]) -> x * y
  | (h1::t1, h2::t2) -> 
        let sc : int = scalar2 (t1,t2) 
        sc + (h1 * h2) 

The error is that scalar2 (t1,t2) reqested to be int, but it is int list * int list -> int

How this problem could be solved?

Upvotes: 1

Views: 49

Answers (1)

kaya3
kaya3

Reputation: 51132

When defining a function using the function keyword, you don't need to name your parameters (a and b here). Note that your function body doesn't refer to a or b at all. You want scalar2 to be a function, and the function expression on the right hand side results in a function, so just assign this function to scalar2 directly.

let rec scalar2 = function
  | ([], []) -> 0
  | ([x : int], [y : int]) -> x * y
  | (h1::t1, h2::t2) -> 
        let sc : int = scalar2 (t1,t2) 
        sc + (h1 * h2) 

Your mistake is likely caused by a confusion with the usual way of defining a function, which doesn't use the function keyword:

let rec scalar2 (a,b) =
  match (a,b) with
  | ([], []) -> 0
  | ([x : int], [y : int]) -> x * y
  | (h1::t1, h2::t2) -> 
        let sc : int = scalar2 (t1,t2) 
        sc + (h1 * h2) 

This way you need a match expression which does use the parameters a and b.

Note that both of these definitions are incomplete, since you haven't said what should happen when only one of the lists is non-empty.


To explain the type error in the original code, consider how F# evaluates let sc : int = scalar2 (t1,t2). Your original definition says that scalar2 (a,b) = function ..., and the left-hand side of this equality has the same form as the expression scalar2 (t1,t2).

So the scalar2 (t1,t2) gets replaced with the function ... expression, after substituting t1 for a and t2 for b. This leaves let sc : int = function ... which of course doesn't type-check.

Upvotes: 3

Related Questions