I am new with Ocaml, my problem is: I have 2 char lists. I want to put in another list the common characters of the 2 lists (error. My base code is this (error in the "check ->hd1<- tl2"):
let rec check list1 list2 = match list1, list2 with
| hd1::tl1, hd2::tl2 when hd1 = hd2 -> hd1
| hd1::tl1, hd2::tl2 -> check hd1 tl2
| [],[] -> ' '
| _::_,_ -> ' '
| [],_::_ -> ' ';;
check ['l'; 'e'; 'l'; 'l'; 'o'] ['h'; 'e'; 'o'];;
My biggest problem is how to fix a list and go forward on the other?
Another problem is to delete a character when I find it. (example: list1= "hello" list2="helo" when the first "l" was found, list2="heo" final_list-->"helo").
I have to learn better this concept of pattern.
let check l1 l2 =
List.fold_left ( fun linter e1 ->
if List.exists ((=) e1) l2 then e1::linter
else linter
) [] l1;;
Test:
# check ['l'; 'e'; 'l'; 'l'; 'o'] ['h'; 'e'; 'o'];;
- : char list = ['o'; 'e']
Some explanations
List.exists
: checks if e1
is in l2