Reputation: 377
I know this could be stupid question, but since I'm new to Ocaml, please give me some tips on defining functions with specific type.
I want to define function which type has int * int * (int -> int) -> int
So I made a function like this.
let rec sigma a b func:int->int=
if a >= b then func(a)
else func(a) + sigma(a+1, b, func)
But sigma function here does not have type int * int * (int->int) -> int
. Instead its type is int->int->(int->int)->int.
How should I define function sigma to have type int * int * (int->int) -> int
?
(Error Message :
Error: This expression has type 'a * 'b * 'c
but an expression was expected of type int
Upvotes: 0
Views: 1029
Reputation: 35210
The type int * int * (int->int) -> int
denotes a function that takes a 3-tuple and returns and integer. A tuple (pair, triple, quadruple, etc) is written as (a,b,c,...)
, e.g.,
let rec sigma (a,b,func) : int =
if a >= b then func(a)
else func(a) + sigma(a+1, b, func)
With all that said, it is usually a bad idea to pass arguments via tuples in OCaml. It hampers currying, inefficient (each tuple is boxed into a separate value), and in general non-functional and not nice.
Also, when you constrain a parameter of a function, you shall parenthesize it, e.g., (func : int -> int)
.
And normally functions in OCaml are applied by juxtaposition of a function name and its arguments, e.g., given a function add
let add x y = x + y
we can apply (call it) just as add 3 5
(not add(3,5)
!)
Therefore, the conventional way to define your sigma function would be
let rec sigma a b func : int =
if a >= b then func a
else func a + sigma (a+1) b func
Upvotes: 1