Search code examples
moduleocamlsignature

OCaml modules and signatures


In my exercise I have to write OCaml module given its signiture:

module type Range
 = sig
   type t
   val range : int * int -> t
   (*val list_of_range : t -> int list*)
 end

The module I have so far:

module Range = 
  struct
  type t = int
  let range (n,m) = 
    if m > n then () else (n,m)
  end

The task for range (n,m) is to take 2 integers and if n <= m then give out a tuple (n,m). Otherwise (). If I try to run this code, I get error The expression has 'a * 'b but an expression was expected of type unit. Can anyone help me to move forward with this?

PS. It's my first day with OCaml.

PPS. I have commented out the list of range.. part because this is the second part of the exercise and wouldn't work anyway if the first part isn't working.

UPDATE

I have updated my code and results seem promising.

module type Range
 = sig
   type t
   val range : int * int -> t
   val list_of_range : t -> int list
 end

module Range = 
  struct
  type t = int

  let range (m,n) = 
    if m > n then (0,0) else (m,n)      

  let rec list_of_range (m,n) = 
    let t = range(m,n) in 
    let x = fst(t) in let y = snd(t) in
    if x = 0 && y = 0 then [0] else x :: list_of_range(x+1,y)
  end

The code above gives me almost perfect expected result. If I give input (1,5), the result is [1;2;3;4;5;0]. The problem is the 0 as the last element in the list. Why is is there? Where does it come from?


Solution

  • the issue comes from your function range, it cannot return a unit type (i.e. () ) and a tuple. In addition, it violates the signature, where you define range as a function that returns an int.