I'm using OCaml 5.3.0.
I like to write open List
at the top of my source files, since I use list functions so frequently that I don't want to have to prefix them as e.g. List.length
or even L.length
. However, that pulls the declaration type 'a t = 'a list
into my namespace. That has an annoying side effect: when VS Code displays a list type, it uses the t
name so that I see e.g. int t
rather than int list
.
So is there some way I can open List
without pulling in t
? In Haskell I could write import List hiding (t)
, but I don't see an equivalent in OCaml.
I'm using OCaml 5.3.0.
I like to write open List
at the top of my source files, since I use list functions so frequently that I don't want to have to prefix them as e.g. List.length
or even L.length
. However, that pulls the declaration type 'a t = 'a list
into my namespace. That has an annoying side effect: when VS Code displays a list type, it uses the t
name so that I see e.g. int t
rather than int list
.
So is there some way I can open List
without pulling in t
? In Haskell I could write import List hiding (t)
, but I don't see an equivalent in OCaml.
2 Answers
Reset to default 1I found one possible way, which is a bit tricky. I can make a source file util.ml
and put this into it:
include (List : module type of List with type 'a t := 'a list)
open List
That says to include List
in the Util
module, but replace the type 'a t
with 'a list
. Now Util
will contain all the List
functions but not List.t
, so in other source files I can write
open Util
You could try to alias your type t
before you open List
and then revert that afterwards. I don't use VS Code, so I don't know for sure if this will work.
Something like:
type t = ...
type t' = t
open List
type t = t'
You may also be looking for more localized versions of opening a module.
E.g.
let double_and_sum lst =
List.(
lst
|> map (( * ) 2)
|> fold_left (+) 0
)
Or:
let double_and_sum lst =
let open List in
lst
|> map (( * ) 2)
|> fold_left (+) 0
In both of these cases it's reasonably clear where the functions are coming from.
List
module functions. – Chris Commented Mar 27 at 6:47length
then? It may just as well mean the length of an array, or string, or of anything else. It is unnatural to define this function name for lists specifically, and it is error-prone. What if you also openArray
? Also, how can I easily identify wherelength
comes from, without advanced editor support for OCaml? Short aliases likemodule L = List
are much better. – Maëlan Commented Mar 27 at 15:03L.length
is normal. Perhaps I will eventually switch to those conventions, but am not yet completely convinced that I want to. :) – Adam Dingle Commented Mar 28 at 7:26