1
votes

Consider, I have a this code.

let firstDigitIsBigerOrEqual (dig1: int) (dig2:int)= dig1>=dig2

let rec computeNumber( numbersInCharacterList:List<int>)=function
      | [] -> 0
      | [single] ->  single
      | firstDigit::secondDigit::tail   when       firstDigitIsBigerOrEqual firstDigit secondDigit   -> firstDigit  + secondDigit+ computeNumber tail
      | firstDigit::secondDigit::tail   when  not (firstDigitIsBigerOrEqual firstDigit secondDigit)  -> secondDigit - firstDigit + computeNumber tail

I have an error in the 2 last lines:

The type 'int list -> int' does not match the type 'int'

I need to get an int as my output of y function. What is wrong with my code?

2
Hint: you're not using numbersInCharacterList. - ildjarn

2 Answers

4
votes

As mentioned by @ildjarn, you're not using the numbersInCharacterList parameter. This is a very easy mistake to make. When you want to write a function that pattern matches on its input, you have two ways of doing that.

By defining normal function and using match construct:

let rec someRecursiveFunc inputList =
  match inputList with
  | [] -> 0
  | x::xs -> 1 + someRecursiveFunc xs

Or, by defining the function using the function keyword:

let rec someRecursiveFunc = function
  | [] -> 0
  | x::xs -> 1 + someRecursiveFunc xs

In the second case, the function has an implicit (anonymous) parameter that we are immediately pattern matching on. Your code mixes the two - it has explicit parameter, but then uses function.

0
votes

You don't need to state the parameter for the function when using a pattern matching function. So in your example, remove numbersInCharacterList:List<int> so your function signature is:

let rec computeNumber = function
    //rest of code...

From MSDN Match Expressions:

// Pattern matching with multiple alternatives on the same line.  
let filter123 x =
    match x with
    | 1 | 2 | 3 -> printfn "Found 1, 2, or 3!"
    | a -> printfn "%d" a

// The same function written with the pattern matching
// function syntax.
let filterNumbers =
    function | 1 | 2 | 3 -> printfn "Found 1, 2, or 3!"
             | a -> printfn "%d" a

Notice x is not in the function signature when using function syntax (2nd example).

If you look at the signature of your function it is:

val computeNumber : numbersInCharacterList:int list -> _arg1:'a -> int

Notice the _arg1 and numbersInCharacterList:int - you now have 2 parameters instead of 1.