What does val mean in Ocaml - ocaml

When seeing documentation of modules in Ocamel there is something like this for example in Graphics Module
val close_graph : unit -> unit
Or when writing a function in an interactive mode:
# let x () = 3;;
val x : unit -> int = <fun>
there is val x : unit -> int = <fun>, What is val and it's use case?

Well, val is a keyword in OCaml with several different uses.
The cases you mention are both, in essence, that val is used in a module signature to specify values that appear in the module. Values are things like functions and expressions. (An example of something that's not a value that can appear in a module is a type.)
You can read about module signatures in the OCaml manual.
The first variant of the nonterminal specification is the one that begins with val.
(In the toplevel, you are creating a module as you type in your definitions. So the toplevel is using signature-style syntax to show what you've defined. So it seems to me anyway.)

Related

OCAML module contains type variables that cannot be generalized

Code:
let size = 10
let getTbl = Array.init size ~f:(fun _ -> Avltree.empty )
end
Error:
Error: The type of this module,
sig val size : int val getTbl : ('_weak1, '_weak2) Avltree.t array end,
contains type variables that cannot be generalized
How do I let the Ocaml compiler know that I plan to store both my key's and values as ints?
Have tried a few different approaches - none of which have worked.
Weak type variables denote types that are not yet inferred, usually because you have defined a program variable and never used it, so the type checker has no idea what this variable contains. It is fine, in general, as the first usage of the variable will define its type. However, since the whole type checking routine in OCaml is bounded by the scope of a compilation unit (i.e., a file), such variables should be defined before you compile your file.
Therefore, you have to either (1) use the variable, (2) constraint it to some type, e.g., (let getTbl : (int, int) Avltree.t array) .. in the implementation (.ml) file, or (3) in the mli file. You can even just create an empty .mli file (with the same name as you .ml file) and this will automatically hide all variables defined in your module and enable compilation.
It might work to change Avltree.empty to (Avltree.empty : (int, int) Avltree.t)

Declaring a function without printing the signature [SML]

Is it possible to declare a function in SML without printing the signature?
I found out that you can print a string without printing val it = () : unit by doing:
val _ = print("Test1");
Is it possible to the same with functions? something like:
val _ = fun foo x = x + 5;
foo 10;
The following program won't compile in SML.
I'm know that I can use let\local but then I can't use them outside the closure. Also I am looking for a way, without importing additional libraries.
What you ask of relates only to the REPL, as function signatures are only printed in the REPL. You can avoid for functions (or other value declarations) to show up by defining them in a local scope, as you suggest (let, local or opaque struct).
A little hack is that multiple re-definitions in a row will yield the latest definition, but then you still need one at the end.
If you want to re-use a value in your code without the REPL printing it, perhaps you are looking to completely disable REPL declaration output, or run a compiled binary?
In Moscow ML you can run the REPL without declaration output with
mosml -quietdec file.sml
But with SML/NJ and others I don't know.

how to search for OCaml functions by name and type

In Haskell, there are two main ways to look up information on functions.
Sites like Hoogle and Stackage. These sites provide two main types of searching:
Searching for the name of a function. For example, here is a search on Hoogle for a function called catMaybes.
This search returns the type of the catMaybes function, as well as the package and module it is defined in.
The major use-case for this type of search is when you see a function used somewhere and you want to know its type and what package it is defined in.
Searching for the type of a function. For example, here is a search on Hoogle for a function of type [Maybe a] -> [a].
This search returns multiple functions that have a similar type, the first of which is catMaybes. It also returns the package and module catMaybes is defined in.
The major use-case for this type of search occurs when you are writing code. You know the type of the function you need, and you're wondering if it is already defined somewhere. For example, you have a list of Maybes, and you want to return a list with all the Nothings removed. You know the function is going to have the type [Maybe a] -> [a].
Directly from ghci. In ghci, it is easy to get information about a function with the :info command, as long as the function is already in your environment.
For example, here is a ghci session showing how to get info about the catMaybes function. Note how you must import the Data.Maybes module first:
> import Data.Maybe
> :info catMaybes
catMaybes :: [Maybe a] -> [a] -- Defined in ‘Data.Maybe’
>
:info shows both the type of the catMaybes and where it is defined.
In OCaml, what sites/tools can be used to search for functions by name or type?
For example, I'm reading through Real World OCaml. I came across some code using the |> function. I wondered if there was a function <| for composing the opposite way. However, I don't know of any way of searching for a function called <|. Also, I don't know of any way of figuring out where |> is defined.
Based on the linked code above, I guess the |> would either have to be in Pervasives or somewhere in Jane Street's Core, but it would be nice to have a tool that gave the exact location.
awesome-ocaml has a section on dev tools that should be helpful.
ocamloscope (github) is sort of an Hoogle for OCaml. Search by name works well. Search by type is less good.
For local search by name, ocp-browser provides a convenient TUI.
In your editor, merlin and ocp-index can do lookup-to-definition and lookup-documentation.
There is a WIP public instance of odig here with a lot (but not all) packages. You can use odig locally too, as stated in another answer.
P.S. The function you are looking for is ##, and it's in the standard library.
The ocp-index package provides a basic facility for searching API functions, e.g.,
$ ocp-index locate '|>'
/home/ivg/.opam/devel/build/ocaml/stdlib/pervasives.ml:39:0
The ocp-browser is a beautiful interface to this utility.
They are all integrated with Emacs (and other popular text editors). Speaking of text editors and IDE, Merlin is a killer feature without which I can't imagine OCaml coding anymore. It is capable of jumping directly to the definition, extracting documentation and incremental typechecking.
Speaking of web-based search, there was an argot document generator that has an API search engine featuring type search, full-text search, and regular expressions. A project is somewhat abandoned and doesn't work with the latest OCaml.
We forked it, update to the latest OCaml, fixed a few bugs, and enhanced the unification procedure to get a better type search. The result can be found here.
One of the main features is a search by type manifest, that ignores such irrelevant things as parameter ordering in functions, field names, differences between record names and tuples (e.g., string * int is the same as {name : string; age : int}) and aliasing. For example, in our project there are quite a few aliases, e.g., type bil = stmt list = Stmt.t list = Stmt.t Core_kernel.Std.list = .... You can choose any name when you search (using type manifest), as the algorithm will correctly unify all aliases.
odig may be helpful. once installed, you can browse by package and by function.

Functors in OCaml: triple code duplication necessary?

I'd like to clarify one point: currently it seems to me that triple signature duplication is necessary while declaring a functor, provided we export it in the .mli file. Here is an example:
Suppose we have a functor Make, which produces a module A parametrized by SigA (simplest example I could think of). Consequently, in the .mli file we have:
module type A = sig
type a
val identity : a -> a
end
module type SigA = sig
type a
end
module Make (MA:SigA) :
A with type a := MA.a
Now I understand that we have to write an implementation in the .ml file:
module Make (MA:SigA) = struct
type a = MA.a
let identity obj = obj
end
So far so good, right? No! Turns out we have to copy the declaration of A and SigA verbatim into the .ml file:
module type A = sig
type a
val identity : a -> a
end
module type SigA = sig
type a
end
module Make (MA:SigA) = struct
type a = MA.a
let identity obj = obj
end
While I (vaguely) understand the rationale behind copying SigA (after all, it is mentioned in the source code), copying A definition seems like a completely pointless exercise to me.
I've had a brief look through the Core codebase, and they just seem to either duplicate it for small modules and for larger once they export it to the separate .mli, which is used both from .ml and .mli.
So is it just a state of affairs? Is everyone fine with copying the module signature THREE times (once in the .mli file, two times in the .ml file: declaration and the definition!!)
Currently I'm considering just ditching .mli files altogether and restricting the modules export using signatures in the .ml files.
EDIT: yes I know that I can avoid this problem by declaring the interface for A inline inside Make in the .mli file. However this doesn't help me if I want to use that interface from outside of that module.
That's because a pair of ML and MLI file acts like a structure and a corresponding signature it is matched against.
The usual way to avoid writing out the module type twice is to define it in a separate ML file. For example,
(* sig.ml *)
module type A = sig
type a
end
module type B = sig
type b
val identity : b -> b
end
(* make.mli *)
module Make (A : Sig.A) : Sig.B with type b = A.a
(* make.ml *)
module Make (A : Sig.A) =
struct
type b = A.a
let identity x = x
end
It is fine to leave out an MLI file in the case where it does not hide anything, like for the Sig module above.
In other cases, writing out the signature separately from the implementation is a feature, and not really duplication -- it defines the export of a module, and usually, that is a small subset of what's in the implementation.

Is there a way to print user-defined datatypes in ocaml?

I can't use print_endline because it requires a string, and I don't (think) I have any way to convert my very simple user-defined datatypes to strings. How can I check the values of variables of these datatypes?
In many cases, it's not hard to write your own string_of_ conversion routine. That's a simple alternative that doesn't require any extra libraries or non-standard OCaml extensions. For the courses I teach that use OCaml, this is often the simplest mechanism for students.
(It would be nice if there were support for a generic conversion to strings though; perhaps the OCaml deriving stuff will catch on.)
There's nothing in the base language that does this for you. There is a project named OCaml Deriving (named after a feature of Haskell) that can automatically derive print functions from type declarations. I haven't used it, but it sounds excellent.
http://code.google.com/p/deriving/
Once you have a function for printing your type (derived or not), you can install it in the ocaml top-level. This can be handy, as the built-in top-level printing sometimes doesn't do quite what you want. To do this, use the #install-printer directive, described in Chapter 9 of the OCaml Manual.
There are third-party library functions like dump in OCaml Batteries Included or OCaml Extlib, that will generically convert any value to a string using all the runtime information it can get. But this won't be able to recover all information; for example, constructor names are lost and become just integers, so it will not look exactly the way you want. You will basically have to write your own conversion functions, or use some tool that will write them for you.
Along the lines of previous answers, ppx_sexp is a PPX for generating printers from type definitions. Here's an example of how to use it while using jbuilder as your build system, and using Base and Stdio as your stdlib.
First, the jbuild file which specifies how to do the build:
(jbuild_version 1)
(executables
((names (w))
(libraries (base stdio))
(preprocess (pps (ppx_jane ppx_driver.runner)))
))
And here's the code.
open Base
open Stdio
type t = { a: int; b: float * float }
[##deriving sexp]
let () =
let x = { a = 3; b = (4.5,5.6) } in
[%sexp (x : t)] |> Sexp.to_string_hum |> print_endline
And when you run it you get this output:
((a 3) (b (4.5 5.6)))
S-expression converters are present throughout Base and all the related libraries (Stdio, Core_kernel, Core, Async, Incremental, etc.), and so you can pretty much count on being able to serialize any data structure you encounter there, as well as anything you define on your own.