john
john

Reputation: 87944

Function definition syntax

I'm trying to implement a particular algorithm. The algorithm isn't very well described but I do have an OCaml implementation. Problem is I don't know OCaml and I'm finding the syntax strange. So here's the first of what might be many questions. Apologies for any mistakes in terminolgy.

One part of the code I have looks like this

type alternative_text = string
type indent = int

module Line =
  struct
    type t = {s:alternative_text; i:indent}
    let make s i = {s;i}
    let text (l:t): alternative_text = l.s
    let length l = String.length l.s
    let indent l = l.i
  end

My question concerns the line let text (l:t): alternative_text = l.s. I think I know what this is, a function Line.text which takes a Line.t object and returns the s field, which is a string.

My question concerns the (l:t): alternative_text syntax. This looks like it's specifying the type of the parameter and function result, but why is it necessary? As far as I know let text l = l.s would do exactly the same thing and the other functions are defined without using this extra syntax. So why is it being used here?

Thanks in advance.

Upvotes: -1

Views: 65

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

The problem with records is that their field names have a scope that's outside the record. So if you have two records with the same field name a, they will clash. I.e., it won't be possible in general to tell whether x.a refers to a field in one record type or the other record type. Depending on the type of x, it could be either.

OCaml tries to give a lot of flexibility in this area by inferring the record type (of x in this example). But if it can't be inferred you need to specify which type you're talking about.

As a side note @glennsl is correct. If you have a non-trivial amount of OCaml to figure out, and you're learning OCaml from scratch, it will be faster to learn OCaml from a book or an online tutorial than to ask individual questions here on StackOverflow.

Upvotes: 1

Related Questions