0
votes

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.

1
If you don't know a language, the best way to learn it is usually to follow a book or tutorial. This is a good one IMO. Stack Overflow is really not suited as a substitute for proper learning resources. - glennsl
Here's the relevant page on function definitions: cs.cornell.edu/courses/cs3110/2019sp/textbook/basics/… - glennsl
@glennsl Thanks for the reference. I have been looking at the tutorials on the OCaml website but that book seems like it will be more useful. But my question remains, why are the types being explicitly specified for the text function but not for the others? - john
Yeah not saying it's not a valid question, but learning the language through a proper resource could help focus the question and enable you to experiment more with it on your own. And for the record, I don't know why it would be necessary. It doesn't seem like it should be. Perhaps it's just to show off different syntax? The context is probably relevant here. - glennsl
Hi @john, the link that Glenn posted answers your question. - Yawar

1 Answers

1
votes

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.