Lavair
Lavair

Reputation: 946

Is there a way to add an empty element to a list in OCaml?

Consider a given list [3;4;5].
Now, I want to execute x::[3;4;5];;
Is there an x in OCaml which leads to the result [3;4;5] again?

Upvotes: 3

Views: 1691

Answers (4)

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12332

No, :: always creates a new list that is one element longer.

What you might be looking for is @ which appends one list to another (actually it prepends the first list before the second). For that you have [] @ list ==> list.

Upvotes: 2

Kevin Ji
Kevin Ji

Reputation: 10489

The other answers are also correct, but I thought it might be helpful to take a look at how list is defined.

Under the hood, list roughly looks like the following:

type 'a list =
  | []
  | ( :: ) of 'a * 'a list

This implies two things:

  1. ( :: ) will always prepend an element to an existing list.
  2. The elements of the list must be of the same type.

So if you have a list [3; 4; 5] already, then x must be an int for x :: [3; 4; 5] to compile.

Upvotes: 6

lambda.xy.x
lambda.xy.x

Reputation: 4998

No they can never be equal - the first one is a list of length 3, the other one is a list of length 4.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370162

No, the result of x::xs is always going to be a list that has one element more than xs does.

If you want to prepend an element to a list conditionally, you'll have to do if condition then x::xs else xs. That is, only use :: in the case where you actually have an element you want to prepend.

Upvotes: 7

Related Questions