How can I use [x] in Ocaml?

for example: when I want to concatenate an int list: [1, 2, 3] with x , my code is:

[1, 2, 3] @ [x]

but in another case, I have a function that takes a list - this is an argument,

 val foo : int list 

I have another print_foo function, taking foo is an argument, and the return type is

 val print_foo : int list list 

I am writing a function: print_foo [foo]

My question is: [foo] in this case is accepted by type checking, but is this true in a logical sense? what is a good way to write this function? This is the same question for [[x]]

Could you explain me more about how and when I can use [x] or [[x]] , etc. ??

Thank you very much,

+4
source share
3 answers

[x] means a list containing one item: x .

[[x]] means a list containing one element: a list containing one element: x .

So, if you say x is 4 , then [x] = [4] is a list containing only 4 , and [[x]] = [[4]] is a list containing only a list containing only 4.

As you can see, [x] just puts x into the list on its own. If x = [1, 2, 3] (that is, x is the list itself), then you probably do not want to call the function with [x] (= [[1, 2, 3]]) , because then you give her a list containing your source list, and not the list itself. Of course, this may be completely legal and necessary in certain cases, but if you are not sure, it most likely will not be needed.

So, if you have foo - this is an int list , and then print_foo [foo] is called, you say: "Print this list containing the list that I want to print." What you probably want to say is print_foo foo , where you leave the list wrapper redundant. This can be interpreted as "Print this list that I want to print."

+3
source

It is always easier if you have types:

An int list is a list containing integers:

 # let x = [1;2;3];; val x : int list = [1;2;3] # List.hd x;; (* return the first element of x *) - : int = 1 

An int list list is a list containing an int list :

 # let y = [x;[4;5]];; val y : int list list = [[1;2;3];[4;5]] # List.hd y;; (* return the first element of y *) - : int list = [1;2;3] 

So.

In addition, if you want to combine the list of integers [1;2;3] with the whole list x , you should use:

 [1;2;3] @ x 

as @ is of type 'a list -> 'a list -> 'a list , i.e. it takes two lists of the same type and returns a new list with the same type.

+3
source

int list list is actall (int list) list , which can be expressed as [an_int_list, another_int_list] or just [the_single_element_which_is_an_int_list] . So foo is an int list , so [foo] is just an int list , which is an (int list) list .

+1
source

Source: https://habr.com/ru/post/1387491/


All Articles