I have start the Ocaml but i have a problem didn't know how resolve it

Hi everyone, I’m new on the forum and I’m a beginner in Ocaml, I’m trying to do an exercise, but I don’t understand at all how lists and couples work

Given an element elm and a list of pairs lcp, write a function nbr_occ that returns the number of pairs whose first component is elm . Example with the data 5 and [(4,5); (5,3); (2,7); (5,2); (5,1)] we will obtain 3

Thank you for your help and your time

Kido

Welcome in the OCaml community !
Usually, it is best to have a more specific question than that when asking homework question.
I think you should at least tell what exactly you dont understand about lists and couples : is the issue understanding what they are, or how to work with them ? If it is how to work with them, what exactly do you think should be doing with them, that you do not know how to do ?

2 Likes

I would suggest to learn the basics of the language. Without reading the first four chapters you won’t be able to code in OCaml and learning the language is a prerequisite for using it and there is no escape hatch here. Don’t hesitate to ask questions if something is not clear, of course.

1 Like

I’m still working out my problem, I’ll try to keep it simple.
I have a list of couple :
[(4,5); (5, 3); (2,7); (5,2); (5,1)]
and one element which is 5 ,

and I must succeed in obtaining as a result the number of couples which has the element 5 located in the first position of the couple (ex: (5,3)) so here 3

But when I try to get by trying to filter my list, I get only errors.

I would like to know how to filter this list of couples and why we use this or that works

Sincerely Kido

Please, as explained earlier, if you expect concrete help, first show us your attempts and failure?

Best regards

Instead of try making filters, try look at the type of List.find, which is ('a -> bool) -> 'a list -> 'a, and figure out how to use this function.

you can use fst : 'a * 'b -> 'a to get the first element of a “couple” (usually we call this a tuple, but there are also 3-tuples, 4-tuples…), and snd for the second element.

Now you should try make a function of int * int -> bool with fst, and feed it to List.find you should get (int * int) list -> (int * int), and you should be able to figure it out how to get the desired result with these.

I suggest after going through the basics, try also get familiar with the standard library, and refer to the source code if feel doubts, and experiment in the repl a few times.

And in addition, if someone asks “show us your attempts and failure”, please don’t be hesitate to show any code you have written for this problem so far, even obviously wrong or can’t be executed, so we can get a better understanding on the situation instead of guessing.