TierTwo
TierTwo

Reputation: 133

How to make a list of type in OCaml?

I have three type :

type position = float * float
type node = position
type edge = node * node * float

And I'd like to make a list of edge by using a list of node by doing this :

let create_type_list nodes_list =
  let rec create_type_list_aux nodes =
    match nodes with
      | [] -> []
      | x::y::l -> Some (x,y, dist2 x y) @ create_type_list_aux l
    in create_type_list_aux nodes_list

dist2 is just a function that calculates the distance between two nodes.

I'm left wondering why such a function can't work and how I could be able to reach my goal of creating a list of type. I have the following error :

Error: This variant expression is expected to have type 'a list
       The constructor Some does not belong to type list

Thanks

Upvotes: 0

Views: 1138

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

The expression you're using to build up the list is presumably this:

Some (x,y, dist2 x y) :: create_type_list_aux l

Indeed this adds an element to the front of the list of type (position * position * float) option. However, the type position is the same as the type node. So this is also type (node * node * float) option. This, in turn is the same as edge option. So your only problem is that you're adding an edge option to your list rather than an edge. You might try using this expression instead:

(x, y, dist2 x y) :: create_type_list_aux l

The only difference is that I removed Some, which is a constructor of the option type.

Upvotes: 1

Related Questions