Ocaml Cheat Sheet

Posted on  by 



The Enviro­nment Model Semantics

When pressing the button (or Ctrl e), the expression under the cursor is sent to the OCaml pane, and the answer from OCaml is displayed there. In case of an error, the relevant part of the code in the editor is highlighted. 2 The OCaml interpreter The command ocaml (without parameters) launches the Caml interpreter. You can type Caml instructions inside and immediately get their result it is highly recommended to use the ledit command with ocaml as argument to make interacting with this inter-preter bearable. For instance, you can type: # let x = 2;; val x: int = 2. Earlier, we dusted-off our language and stdlib cheat-sheets. Because we wanted teachers to be able to give those cheats to their students as quickly as possible, we missed a few typos (special thanks to @hannes, @spop, @Khady, @holmdunc and narimiran for their keen eyes). With more time, we managed to design an opam cheat sheet we are proud of. 🍻 awesome cheatsheet. Awesome Cheatsheet' and other potentially trademarked words, copyrighted images and copyrighted readme contents likely belong to.

Enviro­nment Model Semantics Rule with Lexical Scoping

Technique to Generalize Folding

Genera­lized fold and List folding functions

Function Type Inferrence

Infer the type of functions from operations nested within the function. Start off by labeling all of the bindings and parameters with a random type Tn. And, then find out the type for each of them. Use patterns like the branches of an if and else statements are the same type and same goes for match statem­ents.
Points to note are that the failure ('bl­ah') and Exception Not_found have type 'a (just something random), so they can be restricted to whatever the other type is in a match expres­sion. Also, let rec f x= f x in f has type 'a -> 'b

Ocaml Cheat Sheet 2020

Docume­nting Abstra­ctions

A specif­ication is a contract between an implem­enter of an abstra­ction and a client of an abstra­ction. An implem­ent­ation satisfies a specif­ication if it provides the described behavior.
Locality: abstra­ction can be understood without needing to examine implem­ent­ation
Modifi­abi­lity: abstra­ction can be reimpl­emented without changing implem­ent­ation of other abstra­ctions
Good Specs:
Suffic­iently restri­ctive: rule out implem­ent­ations that wouldn’t be useful to clients
Suffic­iently general: do not rule out implem­ent­ations that would be useful to clients
Suffic­iently clear: easy for clients to understand behavior
Abstra­ction function (AF) captures designer’s intent in choosing a particular repres­ent­ation of a data abstra­ction. Not actually OCaml function but an abstract function. Maps concrete values to abstract values. Think about Set example, where implem­enter sees Set as 'a list [1;2] but user sees it as {1,2}.
Many-t­o-one: many values of concrete type can map to same value of abstract type. [1;2] & [2;1] both map to {1,2}
Partial: some values of concrete type do not map to any value of abstract type
[1;1;2] because no duplicates
opA(AF(c)) = AF(opC­(c)). AF commutes with op!
You might write:
– Abstra­ction Function: comment – AF: comment
Ocaml cheat sheet 2019– comment
Repres­ent­ation invariant charac­terizes which concrete values are valid and which are invalid.
-Valid concrete values will be mapped by AF to abstract values
-Invalid concrete value will not be mapped by AF to abstract values

Substi­tution Model of Evaluation

Substi­tution Model Evalua­tion- Captur­e-a­voiding substi­tution

Example Module & Functor example

Modules Signat­ures, Structures and Functors

Basically, signature is the interface that we must follow for a certain module. The Structure of a module is the implem­ent­ation of the given signature of the module. Furthe­rmore, the functors go ahead and parame­terize modules: that is, they will take in a module or multiple modules as inputs and return a new module that is parame­terized with the input module. So, suppose you have a given Set module and you want this module to applicable to all types not only ints. So, you will need the notion of equality in your module, but this notion of equality is different between Ints and Strings, so you can parame­terize by having a functor that has a type sig of EQUAL as its input. With functors remember to do the sharing constr­aints.

Matching Mechanics & Type Declar­ations

A type synonym is a new kind of declar­ation. The type and the name are interc­han­geable in every way.
Matching: Given a pattern p and a value v, decide
– Does pattern match value?
– If so, what variable bindings are introd­uced?
If p is a variable x, the match succeeds and x is bound to v.
If p is _, the match succeeds and no bindings are introduced
If p is a constant c, the match succeeds if v is c. No bindings are introduced
If p is C p1, the match succeeds if v is C v1 (i.e., the same constr­uctor) and p1 matches v1. The bindings are the bindings from the sub-match.
If p is (p1,..., pn) and v is (v1,..., vn), the match succeeds if p1 matches v1, and ..., and pn matches vn. The bindings are the union of all bindings from the sub-ma­tches.
1. If Expres­sions are just pattern matches
2. Lists and options are just datatypes
3. Let expres­sions are also pattern matches.
4. A function argument can also be a pattern.

Type Checking Rules

Type Checking Rules part of Semantics

Key Points about Modules

Other key points with modules:
1. Difference between include and open is that include just sort of extends a module/ signature when its called. In general, opening a module adds the contents of that module to the enviro­nment that the compiler looks at to find the definition of various identi­fie­rs.W­hile opening a module affects the enviro­nment used to search for identi­fiers, including a module is a way of actually adding new identi­fiers to a module proper. The difference between include and open is that we've done more than change how identi­fiers are searched for: we've changed what's in the module. Opening modules is usuallly not a good thing in top level as you are getting rid of the advantage of a new namespace and if you want to do it, do it locally.
2. Don't expose the type of module especially in the signature, it is smart to hid from your user as they may abuse your invariant and don't have any idea on the implem­ent­ation. So, you can also change the implem­ent­ation without them knowing.
3. We can also use sharing constr­aints in the context of a functor. The most common use case is where you want to expose that some of the types of the module being generated by the functor are related to the types in the module fed to the functor

Data Types VS Record VS Tuple

DeclareBuild/­Con­structAccess/ DestructDataTypetypeConstr­uctor namePattern matching with matchRecordtypeRecord expression with {...}Pattern matching with let OR field selection with dot operator .TupleN/ATuple expression with (...)Pattern matching with let OR fst or sndRecords are used to store this AND that. Datatypes represent this OR that. Also, a tuple is just a record with its fields referred to by position, where as with records it is by name.
Algebraic Dataypes of form <Da­tatype: Name Studen­t> of StringPrintable

Dynamic VS Lexical Scoping

Rule of dynamic scope: The body of a function is evaluated in the current dynamic enviro­nment at the time the function is called, not the old dynamic enviro­nment that existed at the time the function was defined.
Rule of lexical scope: The body of a function is evaluated in the old dynamic enviro­nment that existed at the time the function was defined, not the current enviro­nment when the function is called.

Functions as First Class Citizens

Ocaml cheat sheet 2020Functions are values
Can use them anywhere we use values
First-­class citizens of language, afforded all the “rights” of any other values
– Functions can take functions as arguments – Functions can return functions as results

Ocaml Cheat Sheet

...fun­ctions can be higher­-order
Map: let rec map f xs = match xs with
[] -> []
| x::xs’ -> (f x)::(map f xs’)
map: ('a->'­b)-­>'a­lis­t->­'blist
Filter, Map, folds are iterators basically. They can iterate through structures just like normal loops can.




Coments are closed