Reputation: 946
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
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
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:
( :: )
will always prepend an element to an existing list.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
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
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