OCaml : How to create a list of n 1's in

What is the equivalent of the following Python code in OCaml?

lst = [0] * N

It seems to me that OCaml has not overloaded the * for Lists.

I have written the following function

let makeList i = if i = 0 then [] else 0 :: makeList (i-1) 

Can I do something using a for loop or make the code shorter?

1

4 Answers

OCaml Standard library forms a minimal algebra, suitable for building user libraries on top of it. You should consider to use some of the available community libraries. There're many of them, Batteries, Core, Extlib, Containers, to name a few. If in doubt I would suggest to use Core library, at least because current state of the art OCaml Book is written with this library in mind. In Core there is a List.init function, that suits your needs:

open Core.Std List.init 10 ~f:(const 0);; - : int list = [0; 0; 0; 0; 0; 0; 0; 0; 0; 0] 

There is also a range list, that can make iota lists:

List.range 0 10;; - : int list = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9] 

Install core with

opam install core 

To play with it in the toplevel, use coretop program (installed with core). To compile the program, use corebuild, e.g., assuming that your code is in example.ml:

corebuild example.native 
1

Using ocaml batteries :

List.make n 0 

should make it (I have not tried it)

3

OCaml doesn't overload operators.

There is nothing in the standard library to create such lists, you have to implement it yourself.

Since ocaml 4.06 you can use:

List.init N (fun x->0) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like