3 ms·
i had some of the same problems; here's how i solved them, though keep in mind i am no ocaml expert, just a dabbler at some point i got sick of trying to debug
by kragen 3y ago
i had some of the same problems; here's how i solved them, though keep in mind i am no ocaml expert, just a dabbler
at some point i got sick of trying to debug mysterious compile errors about types in ocaml and started declaring types for all of my function arguments; ocaml lets you do that. an example is http://canonical.org/~kragen/sw/dev3/mukanren.ml http://canonical.org/~kragen/sw/dev3/mukanren.ml (an implementation of a tiny logic programming language, sort of like prolog with superpowers; cw inappropriate intimacy) where, for example, instead of writing
let rec disj g1 g2 t = mplus (g1 t) (g2 t)
i write
let rec
disj (g1 : goal) (g2 : goal) (t : state) = mplus (g1 t) (g2 t)
which is more code, to be sure, but i think easier to understand because it's more explicit. and the compiler doesn't report your type errors in the wrong function anymore when you do that
if you aren't sure what the types should be (easy when parametric polymorphism gets involved) you can paste the code without type declarations into the repl and see what it says
in this case that looks like this
# let rec disj g1 g2 t = mplus (g1 t) (g2 t) ;;
val disj : ('a -> 'b stream) -> ('a -> 'b stream) -> 'a -> 'b stream = <fun>
and in fact my `goal` type is more specific, `state -> state stream`, thus favoring comprehensibility a bit over flexibility (i can always go back and generalize the type more later)
this makes the code a bit more verbose but most functions are more than five words long so it's not actually that bad
maybe i should declare the return type too
let rec
disj (g1 : goal) (g2 : goal) (t : state) : state stream = mplus (g1 t) (g2 t)
but so far parameter declarations seem like about the right balance
declaring parameter types in your own code doesn't help with code you didn't write, but you can use the repl to find out what types the compiler inferred for it
# List.map ;;
- : ('a -> 'b) -> 'a list -> 'b list = <fun>
presumably editors with lsp support have some magic keystroke to display this on demand in your editor or something, maybe an lsp user can tell us what it is
- dazed_confused 3y agoThere is a vscode extension for the ocaml-lsp that will show type annotations above each line of code.
- kragen 3y agoso, no keystrokes, but you can only fit half as much code on your screen?