Editor support: auto-annotate types and other tricks

Sometimes, I find the need to at least temporarily annote types. It helps me narrow down a bad construct.

I was surprised to find out that type annotations could be expressed that way:

(* before *)
let add a b msg =
  print_endline @@ "add log: " ^ msg;
  a + b

(* after *)
let add : int -> int -> string -> int =
 fun a b msg ->
  print_endline @@ "add log: " ^ msg;
  a + b

It makes perfect sens, I like it :slight_smile:

So, thanks to Merlin, I’ve made a little vim function that allows me to do so at the tip of a keystroke:

" vimrc
function! AnnotateType()
        :normal! mz
        :silent MerlinTypeOf
        :silent MerlinYankLatestType
        :execute "normal! 0eea\nfun "
        :normal f=s->
        :normal k$
        :execute "normal! a : \e"
        :normal! "0p$a =
        :normal! =ap`z
endfunction

autocmd FileType ocaml command! -nargs=0 AnnotateType call AnnotateType()
autocmd FileType ocaml nnoremap <LocalLeader>a :AnnotateType<CR>

The nice thing is, when removing the type annotation, ocamlformat automagically collapses the function back into it’s original form.

I’d be interested to hear your tips regarding any editor, something you find useful to your OCaml workflow and not immediately obvious from the get go.

5 Likes