Ocaml compiling list comprehensions

Viewed 175

I want to use ocamlopt to compile list comprehensions. I do not want to use any special libraries, since ocaml supports list comprehensions at least at the top (interactive) level.

Marko Tunjic posted :

list comprehension is already included in standard ocaml

#require "camlp4.listcomprehension";;

[ x * x | x <- [ 1;2;3;4;5] ];;

- : int list = [1; 4; 9; 16; 25]

On ocaml 4.07.1 I found that the following is required on interactive:

#use "topfind";;
#camlp4o;;
#require "camlp4.listcomprehension";;

file lc1.ml contains

open Camlp4.ListComprehensions

let _ = [ x * y | x <- [ 1;2;3;4;5]; y <- [10;11;12;13;14 ] ];;

compile

ocamlfind ocamlopt -package camlp4 -linkpkg lc1.ml -o lc1

File "lc1.ml", line 3, characters 16-17:
Error: Syntax error

expected results

[10; 11; 12; 13; 14; 20; 22; 24; 26; 28; 30; 33; 36; 39; 42; 40; 44;      48; 52;
 56; 50; 55; 60; 65; 70]
1 Answers

First of all a disclaimer. Camlp4 is deprecated so I would highly discourage to use it in any new project. Consider using ppx, or if you really need something that ppx is not able to provide to you, then camlp5 is still at your service.

To build a program that is written in a non-standard OCaml syntax, you need to explicitly tell ocamlfind which syntax you're using, e.g., -syntax camlp4o. This is analogous to the #camlp4o directive of the topfind utility, that you were using.

Next, you don't need to open anything (the open statement in OCaml just extends the current namespace with definitions from the opened module). There is no such module as Camlp4.ListComprehensions, therefore, the correct version of your program is

let _ = [ x * y | x <- [ 1;2;3;4;5]; y <- [10;11;12;13;14 ] ]

and here is the build command

ocamlfind ocamlopt -syntax camlp4o -package camlp4.listcomprehension -linkpkg lc1.ml -o lc1
Related