Search code examples
ocaml

Pattern matching on rest of list


I'm trying to pattern match on a list of pairs, where I'm trying to return a list from the list of pair, however I'm having trouble figuring out where to make the recursive call. Without the recursive call I have this:

let countriesInChart (cht: chart) = 
  match cht with
  | [] -> []
  | (x,y)::tt -> [x;y]
;;

But naturally this only applies to the first pair in the list and simply returns ["countryA"; "countryB"] without the rest of the list.

With the recursive call this simply only returns an empty list:

let rec countriesInChart (cht: chart) = 
  match cht with
  | [] -> []
  | (x,y)::tt -> [x;y]::countriesInChart tt 
;;

How would I make the recursive call such that all the pairs in the list would return as a list?


Solution

  • You have this:

    [x;y] :: countriesInChart tt
    

    This says to add a new list of two elements onto the front of a list of lists.

    I don't think you want a list of lists, you just want a list. So you shouldn't be making a list of two elements.

    If x and y are the same type (as I suspect they are), what you probably want is this:

    x :: y :: countriesInChart tt
    

    This says to add both x and y individually to the front of the recursively generated list.

    You can also write this, which is completely equivalent:

    [x; y] @ countriesInChart tt
    

    However, this constructs a list of two elements only to throw it away. So it's a tiny bit of extra work for no benefit.