Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a matrix module in OCaml

I would like to build a general matrix module, which includes such general operations as length, width, size, read_element, write_element, etc. As a matrix could be defined with several types: element array array, element list list or with map, the advantage of this module is to handle the details of the type of matrix inside it, and do not bother on the level where the module is called. At the moment, I think of something as follows:

module type A_TYPE =
  sig
    type t
  end;;

module matrix =
  functor (Elt: A_TYPE) 
  struct
    type element = Elt.t
    type t = element array array 
      (* `element list list` if I want a matrix to be a list of a list *)

    let length (m: t) : int =
       Array.length a
      (* `List.length a` if t = element list list *)

    ... ...

  end

So from outside, one can write:

module MyInt = struct type t = int end
module MatInt = Matrix(MyInt)
module MyFloat = struct type t = float end
module MatFloat = Matrix(MyFloat)

let m = MatInt.make 3 4 0
let n = MatFloat.make 3 4 0.2

My questions are:

1) I have to define first a module MyInt, then put it into the functor to create MatInt... I found it redundant... Is there a way to instantiate directly a matrix module whose elements have int as type?

2) Considering what is written in (* ... *), is there a way to implement the matrix module such that it handles at same time the different possibilities of type of a matrix? maybe with a pattern-matching?

Hope my questions are clear, could anyone help?

like image 948
SoftTimur Avatar asked Apr 26 '26 21:04

SoftTimur


1 Answers

As for question #1: you don't have to define a MyInt module, you could cut out that step by doing:

 module MatInt = Matrix(struct type t = int end)
like image 173
aneccodeal Avatar answered Apr 30 '26 18:04

aneccodeal