FAQ Database Discussion Community


how return a new type with an update value

functional-programming,ocaml
If I want to change a value on a list, I will return a new list with the new value instead of changing the value on the old list. Now I have four types. I need to update the value location in varEnd, instead of changing the value, I need...

Inserting tuples in a list Ocaml

list,tuples,ocaml,concatenation
I have declared a list l=[];; and now trying to append tuples into this list using '@'. But I am not able to do so. Can anyone please help me sorting this out. let l = [] for x = 1 to 10 do l <- [email protected][(x,x+10)] done;; And want...

Ocsigen/Eliom: How to remove unnecessary JavaScript?

ocaml,ocsigen
I'm taking my first steps in web programming with the Ocsigen framework. I can build simple apps, but I've noticed that Ocsigen generates loads of unnecessary JavaScript code. Even the Hello world example, which has no interactive components at all, generates and includes a 400 KB JavaScript file. Is there...

Bad Indentation of OCaml Comments in vim

vim,ocaml,auto-indent
I use ocamldoc-style comment, but vim is annoying me because it indents the comment when it should not. For instance, with the following code: (** * {[ If I open a new line when being of the second line of the above code, vim will indent the code so it...

In Opam how do I tell which package owns a given file?

ocaml,opam
In Opam how do I tell which package owns a given file under ${OPAMROOT}/system? If there is no direct mean to achieve this, is it possible to list files owned by a given package?

Is there an OCaml equivalent of the [] attribute for DUs in F#?

f#,ocaml,discriminated-union
In F# programs I prefer to use [<RequireQualifiedAccess>] type MyType = | FirstOption of string | SecondOption of int so that in code that uses MyType I am forced to write MyType.FirstOption instead of just FirstOption. Is there any way to force this in OCaml?...

Check element in a list

ocaml
I have an example: let l = [0;1;2] let l1 = [0;2] From the list l check that whether or not there are some element of l is belong to l1; if yes then return a list of pair, for instance [(1,0); (1;2)]...

Ocaml - regexp matching words separated by comma doesn't work

regex,ocaml
I try to know is a string is well formed as a string separated by comma like "foo,bar,bang" and a string like "foo," should be not matched. I don't understand why my regexp doesn't work on the following example : #load "str.cma" let regexp = Str.regexp "[a-ZA-Z0-9]+(,[a-ZA-Z0-9]+)*" let str =...

OCaml: Going from int list list to int

unix,ocaml
I am working on a OCaml motion detection program. It analyzes two images and detects if there was motion. One part requires me summing a row of values and then also summing an entire image. This is what I have currenly: let rec sumImRow(maskedrow) = match maskedrow with | []...

Variant type k has no constructor S

types,ocaml
I am trying to write an implementation for parallel prefix scan using the message passing interface module with the following signature module type S = sig type ('s, 'r) channel val spawn : (('r, 's) channel -> 'a -> unit) -> 'a -> ('s, 'r) channel val send : ('s,...

What does float->float mean in OCaml?

ocaml,ml
I have this type, which defines an expression. I know that * symbol lets me add pairs, but what is the -> for? # type expression = Value of float | Sum of (expr*expr) | Subtraction of (expr*expr) | Fc1 of ((float->float)*expr) ...

Compute the highest value with a given list and operators in OCaml

algorithm,list,ocaml,proof
With a given positive integer list and the addition and the multiplication as operators, I want to compute the highest value. So if my list is [2,3,4], it will be : 2 * 3 * 4 = 24. If there is at least one 1 in the list, it is...

Making socket communication using bin_prot

sockets,ocaml,communication
I want to make Socket communication using bin_prot in OCaml. However, I can't find any detailed explanation or example to do that. I made Socket communication in the other way before, so I know the flow of it. Do you have good explanations or examples to make Socket communication using...

What are the most common bugs in OCaml/Haskell/Scala programs? [closed]

scala,haskell,types,ocaml
Now when we have these fancy type-systems to prevent null-pointer bugs and memory bugs and all, what common bugs are left? Can these bugs be prevented with different type-systems or further programming language research? Edit: Do we know what bugs are common in functional programming? Edit 2: -3 question with...

What is the use of eval `opam config env`?

ocaml
After the installation of opam, it asks to do eval `opam config env`. What is the exact usage of it?...

syntax of polymorphic variable type in OCaml

syntax,ocaml
I'm looking into an OCaml file and I suspect it should be a polymorphic variable type (I don't know OCaml, so maybe very off): type loc = Loc.t and meta_bool = [ BTrue | BFalse | BAnt of string ] and rec_flag = [ ReRecursive | ReNil | ReAnt of...

C99-style hexadecimal floating-point constants in OCaml

floating-point,ocaml,floating-point-conversion
In OCaml, how can I parse C99-style floating-point constants (either as literals or inside strings) in hexadecimal, such as 0x1.b000000000000p4? It seems that they are not valid literals: # let c = 0x1.b000000000000p4;; Characters 12-27: let c = 0x1.b000000000000p4;; ^^^^^^^^^^^^^^^ Error: Unbound record field b000000000000p4 And there seems to be...

Call Rmath via Ctypes from Ocaml on OS X

r,osx,ocaml,dylib
I want to use R's mathematical functions as provided in libRmath from Ocaml. I successfully installed the library via brew tap homebrew science && brew install --with-librmath-only r. I end up with a .dylib in /usr/local/lib and a .h in /usr/local/include. Following the Ocaml ctypes tutorial, i do this in...

Determining in emacs the module in which function is defined?

emacs,ocaml
Say I have the following open A open List let double = map (fun x -> 2*x) [1;2;3] In emacs with merlin-mode I can place the cursor on map and execute merlin-type-enclosing to get the type of map. Is there a similar command (in merlin, tuareg, or others) that can...

OCaml function to return a list of tuples whose last element matches a predicate

ocaml
I am trying to write a function in OCaml that takes a predicate, a list of tuples, and the empty list and returns a list of tuples in that original list whose last member satisfies the predicate. What I have so far is: let rec find_tuples p l l1 =...

OCaml, Sync on two events simultaneous with “and”

multithreading,events,synchronization,ocaml
I wrote an short program with 6 threads and 3 channels. 3 Threads are sending on 2 channels simultaneous and the other 3 are receiving. The problem is now, that it seems, that a sending thread takes one channel, but if it can't take the second one, it keeps the...

Ocamlfind command not found

centos,make,ocaml,opam,ocamlfind
I'm running into an issue installing a package that's reliant on ocamlfind but I'm getting an ocamlfind: command not found error when making. I have installed ocamlfind with the ocaml package manager and have tried reinstalling using "opam reinstall ocamlfind". I have also tried the 'eval opam config env' command...

why the interpreter tell me “This kind of expression is not allowed as right-hand side of `let rec'”

functional-programming,ocaml
I write a ocaml program that parse an arithmetic expression by parser combinator. type 'a parser = char list -> ('a * (char list)) list let return (x: 'a): 'a parser = fun input -> [x, input] let fail: 'a parser = fun _ -> [] let ( >>= )...

Defining a type alias for Hash Table in OCaml

json,ocaml
I am trying to use atdgen and it requires that you define the types of the OCaml objects you're trying to convert to JSON in what it calls an "atd file" So for Hashtbl.t atdgen generates code which looks like: type ('a, 'b) bucketlist = | Empty | Cons of...

OCaml native executable with linked C library

ocaml
What's the simplest command line to produce a native OCaml executable from a set of OCaml and C sources which use a C library that needs to be included via -l<lib>, such as -lm? For instance, the following code illustrates a (contrived) example where it would be necessary: // test.c...

Base64 encode/decode issue

openssl,hex,base64,ocaml
I have two functions to convert to and from base64 using openssl: (* base64 encode *) let encode_base64 msg = let open_ssl_arg = "echo -n '" ^ msg ^ "' | openssl enc -base64" in let ic = Unix.open_process_in open_ssl_arg in let rec output s = try let new_line =...

How a reexport a type in OCaml?

module,ocaml
Let's say I have a module A which is defined as such: type foo = Bar | Baz a module B: open A let string_of_foo = function | Bar -> "bar" | Baz -> "baz" and a module C: open A open B let () = let f = Bar...

Wrapping an exception within another exception in OCaml

exception,ocaml
Can I make an exception which contains another exception in its constructor? I want to throw an exception about what exception happened lower down.

OCaml error: Unbound module Event

multithreading,events,module,compiler-errors,ocaml
I try to build a short ocaml event example. But when I compile, the error in the title appears. The question of: unbound module Event error when compiling Ocaml game was not helpful for me. The system is Kubuntu 14.04 and I installed ocaml over aptitude, so installed packages are:...

Function getting called asynchronously in OCaml

ocaml
I am modifying the facebook/pfff tool, specifically this file. I am appending details (nodes and edge), in graph_code_java.ml, as and when as nodes and vertices are encountered to two separate files: Edges.json and GraphSON.json. In the end, after execution of everything I call function cleanup_graphson, which merges Edges.json and GraphSON.json....

Work with class in OCaml

ocaml
I want create function with my type test_type in class t. My code: type test_type = [`t1|`t2] let get_types = function | `t1 -> "t1" | `t2 -> "t2";; class type class_types = object method t_types : test_type method test : (string -> string -> test_type -> unit) -> unit...

Add two String numbers in Ocaml

string,numbers,ocaml,typeconverting
I’m doing my first steps on Ocaml and I want to write a function which will receive two numbers in String variables and will return the sum of the two received numbers in an string. I know I could do the following let sum a b = match a,b with...

Constant-time list concatenation in OCaml

performance,data-structures,linked-list,ocaml
Is it possible to implement constant-time list concatenation in OCaml? I imagine an approach where we deal directly with memory and concatenate lists by pointing the end of the first list to the beginning of the second list. Essentially, we're creating some type of linked-list like object....

replace camlp4 with camlp5 in utop

ocaml,camlp4,ocamlfind,utop
I'm working with OCaml code that needs camlp5; however, the toplevel (I'm using utop) automatically loads the newer, incompatible camlp4. These are the startup messages: Findlib has been successfully loaded. Additional directives: #require "package";; to load a package #list;; to list the available packages #camlp4o;; to load camlp4 (standard syntax)...

What's the meaning of '()' in OCaml?

function,ocaml
In the book Real World OCaml, I find this code: let command = Command.basic ~summary:"Generate an MD5 hash of the input data" Command.Spec.( empty ... +> anon (maybe_with_default "-" ("filename" %: file)) ) (fun use_string trial filename () -> I see () in the last line (fun use_string trial filename...

Cartesian (outer) product of lists in OCaml

list,polymorphism,tuples,ocaml
I would like to iterate over all combinations of elements from a certain number of lists which have the same length but not necessarily the same type. First I tried to write a general cartesian (outer) product function which takes a list of lists and returns a list of tuples,...

Using Opam to manage project dependencies

dependencies,ocaml,opam
I am a complete newbie to OCaml. Other languages I have used (for instance Scala, Clojure, Javascript on Node.js) have package managers that allow one to start a project as a clean slate that has a declared set of dependencies of known versions. I am trying to do something of...

oasis picks up wrong ocamlbuild

ocaml,ocamlbuild,ocamlfind,oasis
I try to compile an Ocaml project with an Ocaml version provided by Opam. My ocamlbuild, ocamlfind, and oasis seem OK : /Users/fred/.opam/4.02.1/bin/ocamlbuild dhcp-182-73:compil fred$ which ocamlfind /Users/fred/.opam/4.02.1/bin/ocamlfind dhcp-182-73:compil fred$ which oasis /Users/fred/.opam/4.02.1/bin/oasis But when I try to compile, it seems that a wrong version of ocamlbuild is called, and...

Converting GADT to phantom types

ocaml,adt,gadt
I was playing around with GADT and phantom types in OCaml. I understood that GADT is a convenience for describing certain kinds of phantom types—correct me if I'm wrong. So I decided to try out to convert a program using GADT type into an one with ADT and phantom types....

OCaml record acceding itself

ocaml,record
I'm reading an OCaml code where lots of record are defined. These record are defining functions for an interactive command line tool. Type for these records is: { name : string ; help : string ; run : string list -> unit } where name is the name of the...

Ocaml : How compile a file using the module Http_Client.Convenience?

http,ocaml
I'm trying to compile a file using the module Http_Client.Convenience (his documentation is here : Http_Client.Convenience I have the file foo.ml : let result = Http_client.Convenience.http_put "Foo" I'm compiling with this way : ocamlfind ocamlopt -o foo -linkpkg -package netclient foo.ml According to this website Objective Caml, this line should...

OCaml - Accessing absolute paths

ocaml,filepath,qtquick2
I'm developing an application where I implement the GUI in QtQuick and the logic in OCaml, using lablqt. In QtQuick I use a FileDialog to select a file. I need to use the path that the FileDialog returns in my OCaml program but I get an error every time I...

Make OCaml Arg.parse function accept anonymous arguments starting with

parsing,ocaml
I am trying to use the Arg.parse OCaml function to read command line options and arguments, including not specified arguments starting with -. According to the manual: For the user to be able to specify anonymous arguments starting with a -, include for example ("-", String anon_fun, doc) in speclist....

Modify a matrix in ocaml

matrix,ocaml
I want to write a function that is modify every elements inside a matrix. But I have some problem when compiling. Warning 10: this expression should have type unit. I think because all function in ocaml need to return to a value or unit, so if I implement two tasks...

OCaml Types not compatible - OCamlyacc

compiler-construction,functional-programming,ocaml,yacc,ocamlyacc
funcexpr: /* This is a function: arguments -> string list */ LPAREN HEAD arguments RPAREN { let head a = [List.hd (List.hd a)] in head << $3 } | LPAREN REAR arguments RPAREN { let rear b = List.tl (List.hd b) in rear << $3 } | LPAREN ERECT...

Ocaml how to call a method in one class from another class

class,object,ocaml
I'm having some truble with objects and classes. I'm trying to call a method from the class kid in the class family to add a kid in the family anytime I want but I get an error I don't quiet understand. class virtual person name lastName sex = object val...

Why am I getting an error in first case but not in second?

functional-programming,ocaml
I started learning OCaml recently and came across the following problem: *Write a function last : 'a list -> 'a option that returns the last element of a list. * I tried the following code: # let rec last = function | [] -> None | _ :: t ->...

Does OCaml have C-like round() and trunc() functions?

floating-point,ocaml
OCaml's standard library includes several floating-point functions equivalent to C ones, such as mod_float for C's fmod(), the exponentiation operator ** for C's pow(), and other functions such as ceil, log, etc. But does it also include equivalents for round() and trunc()? There is truncate/int_of_float, but their type is float...

What is the use of monads in OCaml?

ocaml,monads
This might be a stupid question, but since OCaml is not pure and has side effects built-in, what is the use of monads in OCaml?

OCaml Graphics.open_graph “Cannot open display …”

emacs,graphics,ocaml,x11
The last line of this code #load "graphics.cma";; open Graphics;; open_graph " 600x400";; returns the following error: Graphics.Graphic_failure "Cannot open display My-Machine.local" Since I use Emacs 24.4 in tuareg mode, on OSX 10.9.5, I've installed XQuartz 2.7.7 and tried to tune it (looked here). I checked whether Graphics is properly...

Struct member selected from type, it is not visible and will not be selected

unix,ocaml
I have a function that uses the Unix lib for its time functions: let rfc822 (t: Unix.tm) : string = Printf.sprintf "%s, %s %s %d %s:%s:%s %s" (List.nth short_days t.tm_wday) (padInt t.tm_yday 2 "0") (List.nth short_month t.tm_mon) (t.tm_year + 1900) (padInt t.tm_hour 2 "0") (padInt t.tm_min 2 "0") (padInt t.tm_sec...

ocaml regex issue on “{{”

regex,ocaml
I am trying to match "{{" in a string: let regexp = Str.regexp_string "{{" let _ = if Str.string_match regexp "a{{hello}}" 0 then print_string "yes" else print_string "no" This prints "no". Why is this not matching? "{" is not a special character: $^.*+?[] Unless I am reading the manual incorrectly,...

OCaml, Collatz sequence, can't print the result

ocaml
I am trying to make a program to compute the length of the Collatz sequence on all numbers from 1 to 100. Basically if I have an odd number I have to multiply it by 3 and add 1(n*3+1), and if I have a even number I need to divide...

Printing a list of lists in OCaml

recursion,ocaml
So I am trying to print a list of lists that would look like this: [0;0;0;0;0]; [0;0;0;0;0]; [0;0;1;0;0]; [0;0;0;0;0]; I can use as many functions as necessary, but only one function may use a print function. Here is what I have so far: let rec rowToString(row) = if (row ==...

Are streams in ocaml really used?

stream,ocaml,ocaml-lwt
Looking at different ocaml projects, I don't see the built-in Streams in the language ever used. Even in the recent Real World Ocaml book, Streams are not mentioned at all, which is odd. What's the reason for that? Is it because Lwt or Core superseed them?...

Basic Oasis or Opam file for a simple OCaml project

ocaml,ocamlbuild,opam,oasis
I am a new OCaml user. I have asked a question to learn how to set up a basic OCaml project, but I still have issues. Jump to the end for a TL;DR For instance, I am trying to learn Irmin. On the home page of Irmin I see I...

#use “str.cma” and #use “name.mli” in Eclipse

ocaml
How do I use "str.cma" in Eclipse? Also, how do I link name.ml to name.mli? I would usually do #use "name.mli" in "name.ml" when using Emacs....

Run bash script from ocaml

ocaml
I think that what i mean is in the title. I have tried to search if it is possible to run bash script from ocaml like from java or from php but i could not find. i know that we can use ocaml as a scripting language but it is...

how create new type in package Yojson Ocaml

json,ocaml
I have json file test.json {"response":[ { "aid":209228783, "thumb_id":"348954492", "owner_id":-79421906, "title":"title1", "description":"description1", "created":"1420821911", "updated":"1421783832", "size":284, "can_upload":1 }, { "aid":205134660, "thumb_id":"353880937", "owner_id":-79421906, "title":"title2", "description":"description2", "created":"1415386976", "updated":"1425057394", "size":308, "can_upload":0 }, { "aid":204502901, "thumb_id":"347548800", "owner_id":-79421906, "title":"title3",...

Is there a good OCaml lib for creating a web service like pyramid in python?

ocaml
The question title says itself. I find pyramid in python is quite easy to use. In OCaml, I know Eliom, but guess it too heavy. And also in client side, I will use angular js and don't need to write browser page in OCaml. Any suggestions?...

Is it possible to get the infinite kind error in Haskell 98?

haskell,functional-programming,ocaml,type-inference,unification
I am implementing a kind system for a new functional programming language and I am currently writing the function to unify two kinds. There are four cases two consider: +---------+---------+-------------------------------------------------------+ | k1 | k2 | action | +=========+=========+=======================================================+ | var | var | k1 := k2 ^ k2 := k1...

Exceptions in Lablgtk callbacks

exception,gtk,ocaml
In Lablgtk, whenever there is an exception in a callback, the exception is automatically caught and an error message is printed in the console, such as: (prog:12345) LablGTK-CRITICAL **: gtk_tree_model_foreach_func: callback raised an exception This gives no stack trace and no details about the exception, and because it is caught...

parsing yaml in ocaml

ocaml,yaml
I am looking for the easiest way to using yaml with ocaml, and I am having a hard time finding a good library for doing this - since I am new to the ocaml community I would am having a hard time separating the small, not all that done, projects...

What's the advantage using lazy evaluation in Queue data structure?

ocaml,lazy-evaluation
I'm reading Purely Functional Data Structures written by Chris Okasaki. In chapter 6, the book introduces lazy evaluation to us, I compared the two version (* https://github.com/mmottl/pure-fun/blob/master/chp5.ml#L47 *) module BatchedQueue : QUEUE = struct type 'a queue = 'a list * 'a list let empty = [], [] let is_empty...

Error: Reference to undefined global `Num'

ocaml,bignum
I'm trying to use the Num module in OCaml (bignums and big fractions). Some things seem to be working, while others seem not to, and I'm not able to generate a single, complete example. For instance: # Num.Int(234);; - : Num.num = Num.Int 234 # Num.mult_num;; Characters -1--1: Num.mult_num;; Error:...

Ocaml can't find Unix module

unix,ocaml,opam
I (re-)installed Ocaml on OS X using the following steps: > brew uninstall ocaml > brew uninstall opam > brew install ocaml > brew install opam > opam init > eval `opam config env` > opam switch 4.02.1 > opam install batteries core I then tried to compile this program:...

Function applied to too many arguments in lablgtk

gtk,ocaml
I need some help understanding why the following code will not compile. I am attempting to place a GSourceView2 inside a vertical box in lablgtk. I've adapted the code from this Ocaml article open GMain open GdkKeysyms let locale = GtkMain.Main.init () let main () = let window = GWindow.window...

Pretty-print in js-of-ocaml

ocaml,pretty-print,js-of-ocaml
I have the following OCaml program open Js let lex s = Compiler.Parse_js.lexer_from_file s let parse s = lex s |> Compiler.Parse_js.parse let buffer_pp program = let buf = Buffer.create 10 in let pp = Compiler.Pretty_print.to_buffer buf in Compiler.Js_output.program pp program; Buffer.contents buf |> print_endline let () = parse "test.js"...

Print tokenization of a string

ocaml,ocamllex
I'm currently working on a programming language as a hobby. It would make lexing errors massively easier to debug if it was possible to have ocamllex print out the tokens it matches as it finds them, I occasionally just add print statements to my rules manually but there should be...

Pack consecutive duplicates of list elements into sublists in Ocaml

ocaml
I found this problem in the website 99 problems in ocaml. After some thinking I solved it by breaking the problem into a few smaller subproblems. Here is my code: let rec frequency x l= match l with |[]-> 0 |h::t-> if x=[h] then 1+(frequency x t) else frequency x...

searching an element in list in ocaml

ocaml
(* function for union of two ordered sets*) let rec search n list1 = match list1 with [] -> false | head :: tail when head = n -> true | head :: tail when head != n -> search n tail ;; (* function calls and output *) Printf.printf("\nList...

Why can't I define the following CoFixpoint?

ocaml,type-inference,coq,induction,coinduction
I am using: $ coqtop -v The Coq Proof Assistant, version 8.4pl5 (February 2015) compiled on Feb 06 2015 17:44:41 with OCaml 4.02.1 I defined the following CoInductive type, stream: $ coqtop Welcome to Coq 8.4pl5 (February 2015) Coq < CoInductive stream (A : Type) : Type := Coq <...

Compiling an OCaml Book example on Hashtbl

ocaml
I've tried to compile the following example open Core.Std module Foo_and_bar : sig type t = S of string | I of int include Hashable.S with type t := t end = struct module T = struct type t = S of string | I of int with sexp, compare...

Three-address code and symbol tables

compiler-construction,ocaml,abstract-syntax-tree,intermediate-language,symbol-table
I am working on a hobby retargetable C compiler in OCaml and I'm building it bottom up. So far I have an annotated AST type, abridged: type 'e expr = | Int of 'e * int | Var of 'e * var | Neg of 'e * 'e expr |...

Ocaml: function cannot return complete resulting list

list,ocaml
I am working on the question from this site, one of the question is asking to return Goldbach conjecture in a given range. My answer works fine for small ranges, but for large range (e.g. 2 - 2000), it only return part of the solution like the following: [(2, (2,...

OPAM: how to locally reinstall a package without re-downloading it?

ocaml,opam
I want to locally recompile/reinstall a package that has already been downloaded via OPAM, but without downloading it again. opam reinstall seems to always re-download the package, and I see no option to disable it. Here are a few reasons one might want to perform this local re-installation: The local...

ocamlbuild specify output location/name

ocaml,ocamlbuild
Can I specify the build location and file name with the ocamlbuild tool? I would like to be able to say (in pseudocode): ocamlbuild myapp.ml -b native -o bin/myapp ...

Difference between Gdk.Window, GtkWindow and GWindow in lablgtk

gtk,ocaml
In Lablgtk, there are (at least) three types of window-named modules: Gdk.Window GtkWindow GWindow What's the difference between them, and how can I go from one to another?...

Functional Breadth First Search

python,haskell,functional-programming,ocaml,sml
Functional depth first search is lovely in directed acyclic graphs. In graphs with cycles however, how do we avoid infinite recursion? In a procedural language I would mark nodes as I hit them, but let's say I can't do that. A list of visited nodes is possible, but will be...

Unit testing OCaml modules with pa_ounit

unit-testing,ocaml,ounit
I have a simple module to test with a few inline pa_ounit tests, i've setup the directory in the oasis style and got it all to build. For a reference I've been using: https://github.com/janestreet/textutils How would one execute the unit-tests for the above repo? I'm assuming there's an executable .ml...

OCaml: Removing duplicates from a list while maintaining order from the right

ocaml
I just read this thread and find it interesting. I implement the remove from the left function in a few minutes: (* * remove duplicate from left: * 1 2 1 3 2 4 5 -> 1 2 3 4 5 * *) let rem_from_left lst = let rec is_member...

OCaml: type inference with polymorphic variants

ocaml,type-inference
Function f argument type is [< 'A | 'B] that's what I want. # let rec f = function | `A -> 0 | `B -> let _ = f in 1 ;; val f : [< `A | `B ] -> int = <fun> However, if I call it...

Generate dump/explain files of Menhir when using ocamlbuild

ocaml,ocamlbuild,menhir
I discovered that Menhir provides --dump and --explain options and it helps debugging a lot. But how can I enable these options under ocamlbuild so that Menhir always generates dump files at compile time? I tried to write myocamlbuild file handling custom tag menhir_dump like the below: ... snip ......

Optimize a file writing operation in OCaml?

file,optimization,ocaml,ml
basically in my project, I am trying to write a list of strings into file like this: val mutable rodata_list : (string*string) list = [] ..... let zip1 ll = List.map (fun (h,e) -> h^e) ll in let oc = open_out_gen [Open_append; Open_creat] 0o666 "final_data.s" in List.iter (fun l ->...

What is the grammar rule for this OCaml code?

syntax,ocaml
I'm not familiar with OCaml, but recently have been analysing the syntax of OCaml. I came across this include construct which I can't see which grammar rule it relates to: include Warning(Loc).S The syntax rule for include is defined as include module-expr and moduule-expr does not allow a dot after...

OCaml |> operator

ocaml
Could someone explain what the |> operator does? This code was taken from the reference here: let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world") I can see what it does, but I wouldn't know how to apply the |> operator otherwise. For that matter, I have...

How to create a record type more than one polymorphic variables

types,polymorphism,ocaml,record
type 'a item = { name:string; quantity:'a };; This is a polymorphic type definition taught in Ocaml class. I'm trying extend this type have more than one polymorphic variables in item type like: type 'a item = { name:string; quantity:'a; price:'b };; But, I'm getting an error with unbound value...

Difference between modules and existentials

module,ocaml,existential-type
It's folk knowledge that OCaml modules are "just" existential types. That there's some kind of parity between module X = struct type t val x : t end and data 'a spec = { x : 'a } data x = X : 'a spec and this isn't untrue exactly....

How does this OCaml code work?

ocaml
The following OCaml code creates a universal type (not mine, from Jane Street's website): module Univ : sig type t val embed: unit -> ('a -> t) * (t -> 'a option) end = struct type t = bool -> unit let embed () = let r = ref None...

OCaml error in basic loop

ocaml
I'm new with OCaml. I'm making a function working this way : I have "tab" in the scope which represents a 2D map, and three parameters, x, y and u. x and y represent the position of the player, and u the direction of the bomb (right, top left etc.)....

Ocaml Product of two polynomials

ocaml,polynomial-math
How to compute the product of two polynomials ? For example: x^3 + 3x^2 +0.2x and 2x^4 + 3 First I made a type Type term = {coefficient:int; name:string; exponent:int};; Type polynomials = term list;; then I made a function calculate coefficient let product l l' = List.concat (List.map (fun...

How to correctly start a process from a specific directory with Lwt

ocaml,ocaml-lwt
It is easy to start a process from a specific directory with Lwt using the functions Sys.getpwd, Lwt_unix.chdir and Lwt_process.exec: Use Sys.getpwd to save the current working directory Use Lwt_unix.chdir to change to the specific directory Use Lwt_process.exec to start the external process Use Lwt_unix.chdir to change to the saved...

How can I add a onclick method using js_of_ocaml?

javascript,ocaml,js-of-ocaml
Hi suppose I have a button with id form-submit and I have the following function in my OCaml file: let () = let form_submit = Dom_html.getElementById "form-submit" in ... What is the right way to add a on_click method to the button? Should I just do something like this? form_submit##onclick...

Using ocamlbuild to build SDL and OpenGL application

opengl,compiler-errors,ocaml,sdl,ocamlbuild
I am trying to create an OCaml program utilizing both ocamlsdl and lablgl, but I can not figure out how to compile it. The relevant information is below: Note: ocamlsdl is not found by ocamlfind. When I go to the lib directory of .opam, I find an ocamlsdl folder, but...

How to declare a reference to a empty stack in OCaml?

reference,ocaml,imperative-programming
perhaps I am being stupid here, so the more general question I want to ask is that how to declare a reference to a empty value of certain type in OCaml. Usually I declare a reference to a custom defined empty value, for example if I have a type type...

passing multiple statements in ocaml using “in” and “and” operations

ocaml,ocamlbuild
I wanted to convert this C++ code to ocaml, but i'm getting syntax error C++ code int** matrix(int n,int **a,int**b) { t=n/2; a11=new int*[t]; for(i=0;i<t;i++) a11[i]=new int [t]; for(i=0;i<t;i++) for(j=0;j<t;j++) a11[i][j]=a[i][j]; a12=new int*[t]; for(i=0;i<t;i++) a12[i]=new int [t]; for(i=0;i<t;i++) for(j=0;j<t;j++) a12[i][j]=a[i][j+t]; a21=new int*[t]; for(i=0;i<t;i++) a21[i]=new int [t]; for(i=0;i<t;i++) for(j=0;j<t;j++) a21[i][j]=a[i+t][j]; }...

Uninstall binary file when removing OPAM package

ocaml,opam
Excerpt from opam file: build: [ ["./configure" "--prefix=%{prefix}%"] [make] ] install: [make "install"] remove: [ ["ocamlfind" "remove" "git-lfs-server"] ] It installs git-lfs-server binary file into %{prefix}/bin directory, but doesn't remove it. How to uninstall it? [make "uninstall"] doesn't work. The package is not in OPAM yet, so I test it...

Calculate the next position of a point in a window

math,geometry,ocaml
Height = 600 Width = 100 I have a point (x,y) that moves and it's initialized at a random position in the beginning, I'd like to calculate it's next position with sin and cos. the next position maybe at ( if i move with 4 pixels ) x+4 y+4 or...

OCaml Unbound value List.assoc

ocaml
I'm compiling a module with a function that calls List.assoc, it fails to build giving me "Unbound value List.assoc" ... i've tried other List functions and they work fine, it also works fine in utop. I can reproduce this by compiling an ml file using corebuild and this code open...

Performance difference between pattern matching and if-else

performance,pattern-matching,ocaml
Why can OCaml generate efficient machine code for pattern matching and not for if-else tests? I was reading Real World OCaml and I came across this section where they compared the performance of pattern matching to the performance of if-else tests. It turned out that pattern matching in their example...