ozgur
ozgur

Reputation: 2719

F# type inference with recursive functions and pattern matching

I have the following F# code

let Operation (l:int list) =
    let A,B = l.[0], l.[1]
    if A > B then (-)
    else if A%2=0 && B%2=0 then (*)
    else (-)

let m =
    function
    | [] -> []
    | x::rest -> rest

let rec ops (l:int list) (opList:int->int->int list) =
    let operation = Operation l
    if l.Length = 0 then opList
    else ops (m l) (operation::opList)

Compiler complains at the last line saying

This expression was expected to have type 'int -> int -> int list' but here has type ''a list'

It is underlying (operation::opList) but operation has the type int -> int -> int and opList has the type int->int->int list. What am I doing wrong here?

Upvotes: 0

Views: 247

Answers (1)

Asik
Asik

Reputation: 22133

This

int->int->int list

is equivalent to

int->int->(int list)

This is a function of two ints that returns a list of ints.

What you mean to write is:

(int->int->int) list

This is a list of functions of two ints that return an int.

So:

let Operation (l:int list) =
    let A,B = l.[0], l.[1]
    if A > B then (-)
    else if A%2=0 && B%2=0 then (*)
    else (-)

let m =
    function
    | [] -> []
    | x::rest -> rest

let rec ops (l:int list) (opList:(int->int->int) list) =
    let operation = Operation l
    if l.Length = 0 then opList
    else ops (m l) (operation::opList)

Upvotes: 2

Related Questions