638 search results for ""
-
Functors
Project Setup
Check that this works using the opam exec -- dune exec funkt command. It shouldn't do anything (the empty file is valid OCaml syntax), but it shouldn't fail either. The stanza libraries str makes
Module System -
Lists
Maps and Iterators
Notice that map2 and iter2 will fail if the lists are of unequal length: There is a variant iter2 for two lists too: In addition, we have an imperative analogue to map , called
Introduction -
A Tour of OCaml
Records
Here, the pattern { age = x; _ } is typed with the most recently declared record type that has an age field of type int . The type int is inferred from the expression 13 <= x && x <= 19 . The
First Steps -
OCaml on Windows
Docker Images
The ocaml/opam Docker Hub repository now contains regularly-updated Windows images. This includes images using msvc and mingw . If you are comfortable with Docker, this might be an easier w
Resources -
Maps
Introduction
When we created the StringMap module, we fed the Map.Make functor the String module to define the type of the map's keys, which we can observe in the StringMap 's signature ( type key stri
Data Structures -
Modules
Module Inclusion
It creates a module Extlib.List that has everything the standard List module has, plus a new uncons function. In order to override the default List module from another .ml file, we need
Module System -
Basic Data Types and Pattern Matching
Unit
The function print_endline prints the string followed by a line ending on standard output. Return of the unit value means the output request has been queued by the operating system. Note : Replace
Introduction -
Using the OCaml Playground
Autocomplete
Autocomplete in the OCaml Playground The playground also supports code completion. It helps users by suggesting and completing their input based on the context.
Resources -
Using the OCaml Playground
Bottom Line
Congratulations! You have made it to the end. Hopefully, by now, you have a better idea how to use the OCaml Playground . Use this to practice the OCaml code and have fun. Happy Hacking!
Resources -
Sets
Adding an Element to a Set
The function StringSet.add with type string -> StringSet.t -> StringSet.t takes both a string and a string set. It returns a new string set. Sets created with the Set.Make functor in OCaml are
Data Structures -
Modules
Stateful Modules
Values returned by Random.bits will differ when you run this code. The first and third calls return the same results, showing that the internal state was reset. A module may have an internal
Module System -
Lists
List Searching
Note that the documentation for filter and partition tells us that the order of the input is preserved in the output. Where this is not stated it the documentation, it cannot be assumed.
Introduction -
Arrays
The Standard Library Array Module
OCaml provides several useful functions for working with arrays. Here are some of the most common ones:
Data Structures -
Arrays
Iterate on an Array
Iterating on arrays can also be made using for loops. Here is the same example using a loop: Array.iter applies a function to each element of an array, one at a time. The given function must
Data Structures -
Options
Fold an Option
Here is the same function, using Option.fold : The Option.fold function can be used to implement a fall-back logic without writing pattern matching. For instance, here is a function that turn
Data Structures -
Using the OCaml Playground
Caveat
In contrast, when you separate these expressions with a ;; , like this , or when you bind them to names, like this , they are evaluated successfully, one after another. A little caveat here is
Resources -
Error Handling
Stack Traces
And you will get a stack trace. Alternatively, you can call, from within the program, To get a stack trace when an unhandled exception makes your program crash, you need to compile the progr
Guides -
Maps
Removing Entries From a Map
Note that the initial map lucky_numbers remains unchanged. Removing a key that isn't present in the map has no effect. To remove an entry from a map, use the remove function, which takes a ke
Data Structures -
Arrays
Introduction
Storing and processing large amounts of data Implementing algorithms that require random access and modification of elements Working with matrices and other multi-dimensional data structures Arrays
Data Structures -
Higher Order Functions
Let-ops
This has the advantage of making code a lot more readable, without changing the behavior we've come to expect from bind calls. Thankfully, OCaml lets us redefine a subset of operators called let-
Introduction -
Options
Bind an Option
Observe that the types are the same, except for the codomain of the function parameter. Here, we display the type of Option.map , with parameters flipped and show a possible implementation of Op
Data Structures -
Options
Map Over an Option
In the standard library, this is Option.map . Using pattern matching, it is possible to define functions, allowing to work with option values. Here is map of type ('a -> 'b) -> 'a option ->
Data Structures -
Higher Order Functions
Binding
To do this with lists we can use the concat_map function, which looks like this: For example, if we have a list and we map over it with a function that returns a list, then we'll have a list of
Introduction -
Options
Introduction
The option type is useful when the lack of data is better handled as the special value None rather than an exception. It is the type-safe version of returning error values. Since no wrapped data ha
Data Structures -
Higher Order Functions
Sorting
Most OCaml modules include a compare function that can be pass in to sort : For lists, this operation returns a new sorted list: For arrays, this operation mutates the array in-place: Bot
Introduction -
Functors
Introduction
Note : The files illustrating this tutorial are available as a Git repo . As suggested by the name, a functor is almost like a function. However, while the inputs and outputs of functions are val
Module System -
Arrays
Sorting an Array
It sorts the provided array in place and in ascending order, according to the provided comparison function. Sorting performed by Array.sort modifies the content of the provided array, which is wh
Data Structures -
A Tour of OCaml
Exceptions
The standard library provides several predefined exceptions. It is possible to define exceptions. Exceptions are caught using the try … with … construction: Note that exceptions do not appe
First Steps -
Loops and Recursions
Approach 1
Get the length of the file and read it all at once using the really_input method. This is the simplest, but it might not work on channels that are not really files (e.g., reading keyboard input)
Introduction -
Maps
Adding Entries to a Map
Note that the initial map lucky_numbers remains unchanged. If the passed key is already associated with a value, the passed value replaces it. To add an entry to a map, use the add function t
Data Structures -
OCaml Programming Guidelines
How to Program
Always put your handiwork back on the bench, then polish it and repolish it.
Resources -
OCaml Programming Guidelines
Credits
Thanks to all those who have already participated in the critique of this page: Daniel de Rauglaudre, Luc Maranget, Jacques Garrigue, Damien Doligez, Xavier Leroy, Bruno Verlyck, Bruno Petazzoni,
Resources -
Sets
Checking if an Element is Contained in a Set
To check if an element is contained in a set, use the StringSet.mem function.
Data Structures -
Error Handling
Printing
Each printer should take care of the exceptions it knows about, returning Some <printed exception> , and return None otherwise (let the other printers do the job). OCaml knows how to print it
Guides -
Sets
Removing an Element from a Set
The function StringSet.remove with type string -> StringSet.t -> StringSet.t takes both a string and a string set. It returns a new string set without the given string.
Data Structures -
Lists
List Scanning
So you can see how the standard library has evolved into its present state: pieces of frequently-used code are turned into useful general functions. This is rather clumsy, though. The standard l
Introduction -
Modules
Conclusion
Functors, which act like functions from modules to modules Libraries, which are compiled modules bundled together Packages, which are installation and distribution units Going further, here are the o
Module System -
Labelled and Optional Arguments
Conclusion
Functions can have named or optional parameters. Refer to the reference manual for more examples and details on labels.
Introduction -
Sets
Introduction
type elt = string for the elements, and type t = Set.Make(String).t for the sets. This module also defines two types: After naming the newly-created module StringSet , OCaml's toplevel displays t
Data Structures -
File Manipulation
Reading
Standard in_channel : stdin Commonly used functions: open_in , open_in_bin , close_in , close_in_noerr Open the file to obtain an in_channel Read characters from the channel. Reading consum
Tutorials -
A Tour of OCaml
Lists
Note that the x :: v pattern in the second matching expression is used to destructure the list into its head x and tail v , where head is the first element of the list and tail is the rest o
First Steps -
Higher Order Functions
Mapping
This is called mapping . For example, if we have a list of users, maybe we want to get a list of usernames. Or if we have an optional password, we may want to encrypt it only if it is set. In cont
Introduction -
File Manipulation
Writing
Standard out_channel s: stdout , stderr Commonly used functions: open_out , open_out_bin , flush , close_out , close_out_noerr Open the file to obtain an out_channel Write to the channel
Tutorials -
Profiling
Arrays
So arrays of floats are unboxed, as expected. (Each float in the array is 8 bytes long.) The assembler syntax is rather complex, but the bracketed expression -4(%ecx, %eax, 4) means "at the ad
Guides -
A Tour of OCaml
Conclusion
In this tutorial, OCaml was used interactively. The next tutorial, Your First OCaml Program , shows you how to write OCaml files, how to compile them, and how to kickstart a project. <!-- 1. Values
First Steps -
Sets
Creating a Set
There's another relevant function StringSet.of_seq: string Seq.t -> StringSet.t that creates a set from a sequence . Converting a list into a set using StringSet.of_list : A set with a sing
Data Structures -
Preprocessors and PPXs
Writing a PPX
If you want to write your own PPX, the place to start is ppxlib's documentation .
Advanced Topics -
Lists
Sorting Lists
The function Fun.flip reverses a binary function parameter order. The function List.sort , given a comparison function of type 'a -> 'a -> int (zero if equal, negative if first smaller, p
Introduction -
Error Handling
Runtime Crashes
Although OCaml is a very safe language, it is possible to trigger unrecoverable errors at runtime.
Guides -
Maps
Checking if a Key is Contained in a Map
To check if a key is a member of a map, use the mem function:
Data Structures