1

Is there a way to construct lists in OCaml without using the :: operator?

For example, I know that normally elements would be concatenated as follows:

1::[2; 3; 4]

which produces [1; 2; 3; 4].

What I'm wondering is if it's possible to implement a method that takes

cons(1 cons(2 cons(3 cons (4 nil))))

and outputs the same result, as shown in the cons Wikipedia page.

Thank you.

1 Answer 1

2

I think that you are looking for List.cons. Which allows you to do

# List.(cons 1 (cons 2 (cons 3 (cons 4 []))));;
- : int list = [1; 2; 3; 4]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I was aware of the List.cons operator, but didn't know it could be used in this fashion. :)
List.(...) just opens the List namespace temporarily. It's a short form of writing List.cons 1 (List.cons 2 (List.cons 3 (List.cons 4 []))) and more focused than writing open List. It's also great for using a modules infix operators like e.g. Vec2D.(a + b * s) without disrupting + everywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.