Anna
Anna

Reputation: 31

Int lists in functions

Does this function take two int lists "x and y" and return an int list of y-x?

let rec fun4 (l: int list) :int list =
  begin match l with | [] -> []
  | [_] -> []
  | x::y::rest -> (y-x)::(fun4 (y::rest)) 
end

Upvotes: 0

Views: 72

Answers (1)

X. Van de Woestyne
X. Van de Woestyne

Reputation: 637

A list is defined as a recursive type:

type 'a list = 
  | [] of 'a list (* the empty case *)
  | ( :: ) of 'a * 'a list

So you basically have two constructors: [] which is the empty list, and x :: other_list which is a list with x as head and other_list as tail. The use of these constructors makes it easy to define a list: [0; 1; 2; 3] is exactly the same of 0 :: 1 :: 2 :: 3 and of (::) (0, (::) (1, (::) (2, (::) (3, [])))) (which is not very pleasant to read).

Recursive algebraic types, here we have the conjunction of sums ([] and (::)) and products (('a * 'a list)), combined with pattern matching make it possible to describe all sorts of common data structures, as well as their functions for consuming, modifying etc.

In your example, you use pattern matching to deconstruct the list:

let rec fun4 my_list = 
  match my_list with 

  (* if my list is empty, I can't process the function so 
     I return the empty list *)
  | [] -> [] 

  (* if my list my list has only one element, I can't process the function
     so, like in the previouse case, I return the empty list *)
  | [ _ ] -> []

  (* Here is the last case of the function, If I almost have two elements in the 
     list. Remember that empty list is also a list ! *)
  | x :: y :: rest -> (y - x) :: (fun4 (y :: rest))

As you can see, Recursives Algebraic data types coupled with pattern matching are a powerful for describing data structures (like list but also many others) and for writing function that use those data structures.

Upvotes: 1

Related Questions